Hi, is it possible to count the number of times a word appears in a given string?
e.g String word= "sony";
String sentence="sony ericsson is a leading company in mobile. sony was found in oct 2001";
In this case the o/p should be 2.
Printable View
Hi, is it possible to count the number of times a word appears in a given string?
e.g String word= "sony";
String sentence="sony ericsson is a leading company in mobile. sony was found in oct 2001";
In this case the o/p should be 2.
Sure, there are many ways to get the number of times the word appears!
Code:int count = 0;
for (Matcher m = Pattern.compile(word).matcher(sentence); m.find(); ++count);
System.out.println(count);
.....Code:int count=0;
for (int i = 0; i != -1; i = sentence.indexOf(word, i+word.length()), ++count);
System.out.println(count);
be creative :D
You can even do it without loops; have a look:
To repeat the previous poster: be creative.Code:public int countOf(String s, String pattern) {
String result= s.replaceAll(pattern, "");
return (s.length()-result.length())/pattern.length();
}
kind regards,
Jos
Oh boy! No doubt that I call you a Java guru :)
Yep, same as with the other solutions given so far. If the OP doesn't want that. a more elaborate test (e.g. word boundaries in a RE or leading/trailing non-letter characters around the word) has to be applied; but let's start with Occam's razor.
kind regards,
Jos