String s=abc 123 abc1234abcabc;String s1=abc; int count=0; int index=0; whileindex=sindexOfs1index!=-1 index+=s1length; count++; Systemoutprintlncount;
This Java code counts the number of occurrences of the substring "abc" in the string "abc 123 abc1234abcabc".
The code initializes a string variable "s" with the value "abc 123 abc1234abcabc" and another string variable "s1" with the value "abc". It also initializes an integer variable "count" to 0 and an integer variable "index" to 0.
The code then enters a while loop that checks for the first occurrence of the substring "abc" in the string "s" using the indexOf() method. If the substring is not found, the loop exits. If the substring is found, the index of the substring is stored in the "index" variable.
The "index" variable is then incremented by the length of the substring "abc". The "count" variable is also incremented by 1.
The loop then continues to search for the next occurrence of the substring "abc" in the remaining part of the string "s" starting from the index where the previous occurrence was found.
Once all occurrences of the substring "abc" have been counted, the code prints the value of the "count" variable, which represents the number of occurrences found. In this case, the output would be "4"
原文地址: https://www.cveoy.top/t/topic/eDVo 著作权归作者所有。请勿转载和采集!