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);
}
}
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
I have split the string into an array of words using
myBuffer.split("\\s")
and compare each of the array elements usingString.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
Solution using
StringBuffer
andStringTokenizer