我有一个字符串数组说

A=["hello", "you"]

我有一根绳子,比如说
s="hello, hello you are so wonderful"

我需要计算As字符串的出现次数。
在这种情况下,出现次数是3(2"hello",1"you")。
如何有效地做到这一点(A可能包含很多单词,s在实践中可能需要很长时间)

最佳答案

public void countMatches() {
    String[] A = {"hello", "you"};
    String s = "hello, hello you are so wonderful";
    String patternString = "(" + StringUtils.join(A, "|")   + ")";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(s);
    int count = 0;
    while (matcher.find()) {
        count++;
    }
    System.out.println(count);
}

注意StringUtils来自apache commons如果不想包含和添加jar,可以使用for循环构造该字符串。

关于java - 计算字符串中数组中的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24657887/

10-13 07:41
查看更多