我正在尝试计算某个字符串在另一个字符串中出现的实例数。我正在搜索的输入字符串未以任何方式格式化。
我目前正在执行以下操作,但很明显它只计算 .contains 一次。多次计算实例的最有效方法是什么。
public String computeBestFitKey() {
if(this.inputText == null)
return null;
String answer = null;
int bestCount = 0, tempCount = 0;
for(String s: logicTemplate.getLogicMap().keySet()) {
String[] keyWords = this.logicTemplate.getKeyWords(s);
for(String word: keyWords) {
if(this.inputText.toLowerCase().contains(word.toLowerCase())) {
System.out.println("word found: "+word.toLowerCase());
tempCount++;
}
}
if(tempCount > bestCount) {
bestCount = tempCount;
answer = s;
}
tempCount = 0;
}
return answer;
}
最佳答案
如果您只需要计算某个单词的出现次数,并且这不是一项限制您使用某些标准工具的家庭作业,那么您可以这样做
int numOccurrences = 0;
Matcher m = Pattern.compile(word, Pattern.LITERAL).matcher(input);
while (m.find()) numOccurrences++;
Pattern.LITERAL
用于按字面意思处理所有字符并忽略其在正则表达式中的特殊含义(如果有)。
关于java - 使用 .contains 检测单词的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27905995/