fin*_*col 5 java arrays arraylist
我有一个字符串列表。对于每个字符串,我希望查看单词“joe”的第一次出现是否存在。例如,我用空格分隔,因为我不想计算“joey”这个词。
我当前的代码计算单词“joe”的每次出现,如何编辑它以便它只计算该单词的第一次出现,然后移至列表中的下一个字符串。
public int counter(List<String> comments) {
int count = 0;
String word = "joe";
for (String comment : comments) {
String a[] = comment.split(" ");
for (int j = 0; j < a.length; j++) {
if (word.equals(a[j])) {
count++;
}
}
System.out.println(comment);
}
System.out.println("count is " + count);
return count;
}
Run Code Online (Sandbox Code Playgroud)
编辑
str.add("the hello my the name is joe the this joe is a test");
str.add("i was walking down joe then suddenly joe said hi");
Run Code Online (Sandbox Code Playgroud)
我希望我的代码为此返回 2 (joe 已出现在每个字符串中)
您可以使用正则表达式来检查整个字符串是否包含该单词,而无需先将其拆分为单个单词。
匹配单词“joe”但不匹配“joey”的正则表达式如下:
\bjoe\b
Run Code Online (Sandbox Code Playgroud)
匹配\b单词的边界,因此整个表达式匹配单词的开头,然后匹配单词(必须是 joe),然后匹配单词的结尾。
在 Java 中,这可以使用matches(pattern)String 上的方法来实现:
"hello joe, how are you?".matches(".*\\bjoe\\b.*");
Run Code Online (Sandbox Code Playgroud)
请注意,该matches函数要求正则表达式匹配整个字符串才能返回 true,因此我们必须.*在开头和结尾处添加,这将匹配任意数量的任意字符。(.匹配任意字符,表示*要匹配前面的子表达式任意次数)
该正则表达式的优点是它仍然适用于标点符号。仅按空格分割将无法识别字符串“hello joe, how are you?”中的 joe。
总而言之,这将是整个解决方案:
public int countMatches(List<String> comments) {
int numberOfMatches = 0;
for (String comment : comments) {
if (comment.matches(".*\\bjoe\\b.*")) {
numberOfMatches++;
}
}
return numberOfMatches;
}
Run Code Online (Sandbox Code Playgroud)
如果要匹配任意搜索词,则必须小心,因为某些字符在正则表达式中具有特殊含义。我建议使用Pattern.quote(import java.util.regex.Pattern;):
String pattern = ".*\\b" + Pattern.quote(word) + "\\b.*";
Run Code Online (Sandbox Code Playgroud)
然后您可以将评论与 进行匹配comment.matches(pattern)。
| 归档时间: |
|
| 查看次数: |
17288 次 |
| 最近记录: |