使用Java快速计算字符串中单词出现次数的方法

使用Java快速计算字符串中单词出现次数的方法,java,regex,find-occurrences,Java,Regex,Find Occurrences,我想使用Java快速高效地查找一个单词在字符串中出现的次数 单词之间用空格隔开,我正在寻找完整的单词 Example: string: "the colored port should be black or white or brown" word: "or" output: 2 对于上面的示例,“有色”和“端口”不被计数,但“或”被计数 我考虑过使用substring()和contains()并迭代字符串。但是我们需要检查周围的空间,我认为这是没有效率的。另外,StringUtils.c

我想使用Java快速高效地查找一个单词在字符串中出现的次数

单词之间用空格隔开,我正在寻找完整的单词

Example: 
string: "the colored port should be black or white or brown"
word: "or"
output: 2
对于上面的示例,“有色”和“端口”不被计数,但“或”被计数

我考虑过使用substring()contains()并迭代字符串。但是我们需要检查周围的空间,我认为这是没有效率的。另外,StringUtils.countMatches()的效率不高

我尝试过的最好的方法是在空间上拆分字符串并迭代单词,然后将它们与给定单词进行匹配:

它应该足够快,并且为string1提供了正确的答案,但对string2没有(注释)。正则表达式似乎需要稍作修改


有什么想法吗?

这个怎么样?假设
word
没有空格

string.split("\\s"+word+"\\s").length - 1;

}我试验并评估了三个答案基于拆分的基于匹配器的(如问题中所述),以及基于集合.frequency()。每次我测量循环中重复1000万次的总时间。因此,基于分割的答案往往是最有效的方式:


基于Matcher的解决方案(在问题中提到)要慢得多(运行时间要多约5倍)。

当您搜索“java快速字符串匹配”或“java快速单词计数”时,您发现了什么?
int output=Collections.frequency(Arrays.asList(string.split(“”))
“彩色端口应为黑色、白色或棕色”。拆分(“或”)。长度-1)?您可以使用Baby的解决方案,在开头和结尾添加空格后,这样您就不会从文件中读取文本了?@NickZiebert,发布您的单独查询,到目前为止,OP只需要一个单词即可搜索
        String string1 = "the colored port should be black or white or brown or";
        //String string2 = "the color port should be black or white or brown or";
        String word = "or";
        Pattern pattern = Pattern.compile("\\s(" + word + ")|\\s(" + word + ")|(" + word + ")\\s");
        Matcher  matcher = pattern.matcher(string1);
        //Matcher  matcher = pattern.matcher(string2);
        int count = 0;
        while (matcher.find()){
            match=matcher.group();
            count++;
        }
        System.out.println("The word \"" + word + "\" is mentioned " + count + " times.");
string.split("\\s"+word+"\\s").length - 1;
public class Test {
public static void main(String[] args) {
    String str= "the colored port should be black or white or brown";
    Pattern pattern = Pattern.compile(" or ");
    Matcher  matcher = pattern.matcher(str);

    int count = 0;
    while (matcher.find())
        count++;

    System.out.println(count);    
}
String string = "the colored port should be black or white or brown";
String[] words = string.split(" ");
String word = "or";
int occurrences = 0;
for (int i=0; i<words.length; i++)
    if (words[i].equals(word))
        occurrences++;
System.out.println(occurrences);
String string = "the colored port should be black or white or brown or";
String word = "or";
int count = Collections.frequency(Arrays.asList(string.split(" ")), word);
System.out.println("The word \"" + word + "\" is mentioned " + count + " times.");