【发布时间】:2017-02-01 04:31:40
【问题描述】:
我想使用 Java 快速有效地查找一个单词在字符串中出现的次数。
单词以空格分隔,我正在寻找完整的单词。
Example:
string: "the colored port should be black or white or brown"
word: "or"
output: 2
对于上面的例子,“colored”和“port”不计算在内,但是“or”被计算在内。
我考虑过使用 substring() 和 contains() 并迭代字符串。但是接下来我们需要检查我认为效率不高的周围空间。 StringUtils.countMatches() 效率也不高。
我尝试过的最好的方法是在空间上分割字符串并迭代单词,然后将它们与给定的 word 匹配:
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);
但我期待一些使用 Matcher 和 regex 的有效方法。
于是我测试了以下代码:
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.");
它应该足够快,并为我提供了 string1 的正确答案,但不是 string2(已评论)。正则表达式似乎需要稍作改动。
有什么想法吗?
【问题讨论】:
-
当您搜索“java 快速字符串匹配”或“java 快速字数统计”时,您发现了什么?
-
int output = Collections.frequency(Arrays.asList(string.split(" ")), word); -
"the colored port should be black or white or brown".split(" or ").length-1);? -
你可以使用Baby的解决方案,在开头和结尾添加一个空格
-
所以您不是从文件中读取文本?
标签: java regex find-occurrences