Abbasi
0
Q:

how to count an replace string in java

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);
}
0
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);
0

New to Communities?

Join the community