使用.contains检测单词的多个实例

时间:2015-01-12 15:59:25

标签: java regex

我正在尝试计算某个字符串在另一个字符串中出现的实例数。我正在搜索的输入字符串没有以任何方式格式化。

我目前正在进行以下操作,但很明显它只计算一次.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;
}

3 个答案:

答案 0 :(得分:1)

您应该使用indexOf(string str, int startFrom)

替换此行:if(this.inputText.toLowerCase().contains(word.toLowerCase())) {

有了这些:

int lastIndex = -1;
String lowerTextInput = this.inputText.toLowerCase();
String lowerWord = word.toLowerCase();
while((lastIndex = (lowerTextInput .indexOf(lowerWord , lastIndex + 1)) > 0)

这样做的是它为你的子字符串赋值lastIndex。如果字符串不包含子字符串,则它将产生-1,因此while条件将中断。如果确实存在,lastIndex的值将增加1并再次进行搜索。

如果您想对此进行一些改进,尤其是在搜索大字符串时,我建议您将lastIndex的值增加您匹配的子字符串的长度。

答案 1 :(得分:1)

如果您只需要计算一个单词的出现次数,并且它不是您被限制使用某些标准设施的家庭作业,那么您可以这样做

int numOccurrences = 0;
Matcher m = Pattern.compile(word, Pattern.LITERAL).matcher(input); 
while (m.find()) numOccurrences++;

Pattern.LITERAL用于字面处理所有字符,并忽略其在正则表达式中的特殊含义(如果有)。

答案 2 :(得分:0)

static int countOccurences(String haystack, String needle)
{
    int index, lastIndex = -1, count = 0;

    while ((index = haystack.indexOf(needle, lastIndex + 1)) != -1)
    {
        lastIndex = index;
        ++count;
    }

    return count;
}
相关问题