在字符串中计算单词出现的次数

21

我是Java字符串的新手,问题是我想要在一个字符串中计算特定单词出现的次数。假设我的字符串是:

i have a male cat. the color of male cat is Black

现在我也不想再分割它了,所以我想搜索一个词是“male cat”,它在我的字符串中出现了两次!

我尝试的是:

int c = 0;
for (int j = 0; j < text.length(); j++) {
    if (text.contains("male cat")) {
        c += 1;
    }
}

System.out.println("counter=" + c);

它给了我46个计数器的值!那么解决方案是什么?


你能描述一下你认为这段代码是如何工作的(或者你希望它如何工作)吗?这将有助于我们更好地帮助你。 - Pshemo
如果你想在 aaaa 中搜索 aa,那么结果应该是 2 还是 3 - Pshemo
我已经给出了一个示例字符串,因此输出应为2,因为“male cat”在该字符串中出现了两次。 - Java Nerd
不了解Java,但根据您想要做什么,如果它有一个非正则表达式查找第一个字符串的工具,每次在循环中指定起始位置(C++的'string'类有这个功能),那么速度应该会更快。 - user557597
1
好的,我查了一下。你所需要的只是 while((newndx=str.indexOf("male cat",oldndx))>-1){found++;oldndx=newndx+8;} - user557597
同类问题在这里得到了解决 ==> https://dev59.com/_HRA5IYBdhLWcg3w9ivq#767910 - Rohit Bavkar
23个回答

43

您可以使用以下代码:

String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
    i++;
}
System.out.println(i); // Prints 2

演示

它是什么?

它匹配"male cat"

while(m.find())

表示在循环内执行给出的操作,同时m找到一次匹配。 而我通过i++增加i的值,因此这显然给出了字符串中male cat出现的次数。


4
干得好。现在 OP 有一段他不理解的代码,但至少它能工作。 - Pshemo

15

如果你只想知道"male cat"的数量,那么我会这样做:

String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);

如果您想确保不匹配"female cat",则在分隔正则表达式中使用\\b单词边界:

int c = str.split("\\bmale cat\\b").length - 1;

1
这真的很容易。在我的一次面试中,他们让我用一两行写下来,这是完美的匹配。再次感谢。 - vijayraj34
1
我猜在字符串以搜索词结尾的情况下,这种方法不起作用。例如:"我有一只公猫。公猫的颜色" - Shyamnath Mallinathan

13

Apache commons-lang中的StringUtils类有一个CountMatches方法,用于计算一个字符串在另一个字符串中出现的次数。

   String input = "i have a male cat. the color of male cat is Black";
   int occurance = StringUtils.countMatches(input, "male cat");
   System.out.println(occurance);

6

Java 8版本。

System.out.println(Pattern.compile("\\bmale cat")
            .splitAsStream("i have a male cat. the color of male cat is Black")
            .count()-1);

5

Java 8 版本:

    public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
    return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}

4

这个 static 方法返回一个字符串在另一个字符串上出现的次数。

/**
 * Returns the number of appearances that a string have on another string.
 * 
 * @param source    a string to use as source of the match
 * @param sentence  a string that is a substring of source
 * @return the number of occurrences of sentence on source 
 */
public static int numberOfOccurrences(String source, String sentence) {
    int occurrences = 0;

    if (source.contains(sentence)) {
        int withSentenceLength    = source.length();
        int withoutSentenceLength = source.replace(sentence, "").length();
        occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
    }

    return occurrences;
}

测试:

String source = "Hello World!";
numberOfOccurrences(source, "Hello World!");   // 1
numberOfOccurrences(source, "ello W");         // 1
numberOfOccurrences(source, "l");              // 3
numberOfOccurrences(source, "fun");            // 0
numberOfOccurrences(source, "Hello");          // 1

顺便说一下,这个方法可以写在一行中,虽然很糟糕,但它也能够工作 :)
public static int numberOfOccurrences(String source, String sentence) {
    return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}

3
为什么不使用递归?
public class CatchTheMaleCat  {
    private static final String MALE_CAT = "male cat";
    static int count = 0;
    public static void main(String[] arg){
        wordCount("i have a male cat. the color of male cat is Black");
        System.out.println(count);
    }

    private static boolean wordCount(String str){
        if(str.contains(MALE_CAT)){
            count++;
            return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
        }
        else{
            return false;
        }
    }
}

3

using indexOf...

public static int count(String string, String substr) {
    int i;
    int last = 0;
    int count = 0;
    do {
        i = string.indexOf(substr, last);
        if (i != -1) count++;
        last = i+substr.length();
    } while(i != -1);
    return count;
}

public static void main (String[] args ){
    System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}

这将显示:2

另一个count()的实现,仅需要1行代码:

public static int count(String string, String substr) {
    return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}

2

公共类TestWordCount {

public static void main(String[] args) {

    int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
    System.out.println("count : "+count);

}

public static int numberOfOccurences(String findWord, String sentence) {

    int length = sentence.length();
    int lengthWithoutFindWord = sentence.replace(findWord, "").length();
    return (length - lengthWithoutFindWord)/findWord.length();

}

}


1
在回答问题时,请勿直接放置代码,而是解释答案。这里有一份文件,详细说明如何回答问题:http://stackoverflow.com/help/how-to-answer - Sumanth Shastry

1
将需要计数的字符串替换为空字符串,然后使用不包含该字符串的长度来计算出现次数。
public int occurrencesOf(String word)
    {
    int length = text.length();
    int lenghtofWord = word.length();
    int lengthWithoutWord = text.replace(word, "").length();
    return (length - lengthWithoutWord) / lenghtofWord ;
    }

最好使用replaceAll()。 - Koustuv Ganguly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接