xxxxxxxxxx
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
xxxxxxxxxx
public static void main(String[] args) throws Exception {
String word = "abcdefg";
System.out.println(word.length());
System.out.println(word.replace("a", "").length());
int a_counter = word.length() - word.replace("a", "").length();
System.out.println(a_counter);
}
xxxxxxxxxx
public class SubstringOccurrenceCounter {
public static int countOccurrences(String string, String substring) {
int count = 0;
int index = 0;
while (index != -1) {
index = string.indexOf(substring, index);
if (index != -1) {
count++;
index += substring.length();
}
}
return count;
}
public static void main(String[] args) {
String string = "Java is awesome and Java is powerful";
String substring = "Java";
int occurrenceCount = countOccurrences(string, substring);
System.out.println("Number of occurrences: " + occurrenceCount);
}
}