Is there any default method in Java that can count total occurrence of a word? For example, how many times stack occurred in a string "stack is stack".
Edit: pleas开发者_如何学JAVAe only Java no third party library.
You can use StringUtils.countMatches(string, "stack")
from commons-lang. This doesn't account for word boundaries, so "stackstack" will be counted as two occurences.
There is no built-in .matchCount()
method. Here is my impl.
public static int matchCount(String s, String find) {
String[] split = s.split(" ");
int count = 0;
for(int i=0; i<split.length; i++){
if(split[i].equals(find)){
count++;
}
}
return count;
}
String s = "stack is stack";
System.out.println(matchCount(s, "stack")); // 2
You could use:
public static int NumTimesInString(String target, String regex)
{
return (" " + target + " ").split(regex).length - 1;
}
This will work so long as regex doesn't match a beginning or ending space... Hmm, this might not work for some cases. You might be better writing a function which uses indexOf
public static int NumTimesInString(String target, String substr)
{
int index = 0;
int count = -1;
while (index != -1)
{
index = target.indexOf(substr, index);
count++;
}
return count;
}
NOTE: not tested
Either one can be used as:
int count = NumTimesInString("hello world hello foo bar hello", "hello");
// count is 3
精彩评论