Java String-buffer - How to count occurrence of specific word in a string

6.4k views Asked by At

All,

I need to count the specific word from a string in stringbuffer. i have made a program (please see below) to count a specific char in a string but not sure how to do this for a word. for example... my string is "Cat can kill mouse but mouse can not kill cat". I need to count how many times word cat occurred in the string.

thank you so much for your help. Kind Regards,

Viku

public static void main(String[] args) {

    StringBuffer myBuffer = new StringBuffer("a is the first vowel in a e i o u");
    int charCount = 0;
    for(int i =0 ; i< myBuffer.length(); i++){
        if(myBuffer.charAt(i) == 'a' || myBuffer.charAt(i) == 'e' || 
                myBuffer.charAt(i) == 'i' || myBuffer.charAt(i) == 'o' ||
                myBuffer.charAt(i) == 'u'){
            charCount++;
        }
    }
    System.out.println(nL + "Compute of Vowels in String: " + charCount);




}

}

2

There are 2 answers

2
Johny On

Your code is used to count the number of occurrence of vowels in a string and not the no. of occurrence of a particular word in a String. This is my solution.

Solution

String myBuffer = "a is the first vowel in a e i o u";

String checkWord = "a"; // this is the word to match in the string
int count = 0;
for(String word: myBuffer.split("\\s")) {
    if(word.equals(checkWord)) {
        count++;
    }
}
System.out.println(count);

I have split the string into an array of words using myBuffer.split("\\s") and compare each of the array elements using String.equals() method.

In the above code i am checking the occurrence of String "a" in "a is the first vowel in a e i o u".

Output

2

Solution using StringBuffer and StringTokenizer

StringBuffer myBuffer = new StringBuffer("a is the first vowel in a e i o u");
StringTokenizer st = new StringTokenizer(myBuffer.toString());
String checkWord = "a";
int count = 0;

while(st.hasMoreTokens()) {
    String word = st.nextToken().toString();
    if(word.equals(checkWord)){
        count++;
    }
}
System.out.println(count);
1
tharinduwijewardane On

You can split the sentence into an string array and iterate the array to find matching words

String s = String.valueOf(myBuffer);
String[] array = s.split(" ");
for (int i = 0; i < array.length; i++) {
    if(array[i].equals("cat")){
        charCount++;
    }
}