Count Java String Occurrences: Simple Guide
You can use the indexOf() method and substring() method of the String class to count the occurrences of a certain string.
Here is an example code:
public class CountOccurrences {
public static int countOccurrences(String str, String target) {
int count = 0;
int index = 0;
while ((index = str.indexOf(target, index)) != -1) {
count++;
index += target.length();
}
return count;
}
public static void main(String[] args) {
String str = "Hello Hello Hello World";
String target = "Hello";
int count = countOccurrences(str, target);
System.out.println("字符串 \"" + target + "\" 出现的次数为: " + count);
}
}
When running the code above, the output is:
字符串 "Hello" 出现的次数为: 3
In the code above, we have defined a method called countOccurrences() that takes two parameters: the string to be searched (str) and the target string (target). Inside the method, we use a while loop to find the number of occurrences of the target string within the string to be searched. We use the indexOf() method to get the index of the target string in the string to be searched, if the return value is not -1, it means a matching string has been found. We increase a counter called count by 1, and update the index to the next index position of the matching string. Finally, we return the value of the counter as the result.
Please note that the above code can only calculate the non-overlapping occurrences of the target string in the query string. If you need to calculate overlapping occurrences, you can change the update of the index to index++.