我有要求我必须找到否.特定单词出现在文件中的次数.例如.
String str = "Hi hello how are you. hell and heaven. hell, gjh, hello,sdnc ";
Run Code Online (Sandbox Code Playgroud)
现在在这个字符串中,我想要数不.有时"地狱"这个词出现了.伯爵应该包括"地狱","地狱",所有这些词语,但不是"你好".所以根据给定的字符串,我希望计数为2.
我使用了以下方法
第一名:
int match = StringUtils.countMatches(str, "hell");
Run Code Online (Sandbox Code Playgroud)
StringUtils是org.apache.commons.lang3库
第二:
int count = 0;
Pattern p = Pattern.compile("hell");
Matcher m = p.matcher(str);
while (m.find()) {
count++;
}
Run Code Online (Sandbox Code Playgroud)
第3
int count =0;
String[] s = str.split(" ");
for(String word: s)
if(word.equals("hell")
count++;
Run Code Online (Sandbox Code Playgroud)
前两种方法给出4作为答案,第3种方法给出1作为答案.
无论如何,请建议我可以获得2作为答案并满足我的要求.
您可以使用带有"\\ b"字边界的正则表达式,如下所示:
int matches = 0;
Matcher matcher = Pattern.compile("\\bhell\\b", Pattern.CASE_SENSITIVE).matcher(str);
while (matcher.find()) matches++;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
984 次 |
| 最近记录: |