【问题标题】:how to find # of matches of string s in a larger string in java如何在java中的较大字符串中查找字符串s的匹配数
【发布时间】:2012-03-26 06:57:53
【问题描述】:

鉴于以下情况:

String s = "The The The the the the";

如何找出字符串 s 中有多少个“The”?

s.matches("The") 只会告诉我是否至少有一个。 s.contains("The") 也一样。

有什么简单的方法吗?

【问题讨论】:

标签: java regex string


【解决方案1】:

据我所知,Matcher.find() 方法试图找到与模式匹配的输入序列的下一个子序列。这意味着您可以多次调用此方法来遍历匹配项:

int count = 0;
while (matcher.find()) {
  count++;
}

你应该使用 Matcher.start() 和 Matcher.end() 来检索匹配的子序列。

【讨论】:

  • 只是想发布相同的答案。
【解决方案2】:

您可以使用indexOf(str, count)

int count = 0;
String s = "The The The the the the";
String match = "The";
int searchStart = 0;

while ((searchStart = s.indexOf(match, searchStart)) != -1)
{
    count++;
    searchStart+= match.length();
}

【讨论】:

  • 这是一个无限循环
  • 确实,这需要循环体中的searchStart += match.length
  • @ChandraSekhar:我认为你是对的。现在应该修复它。不幸的是,我目前无法测试代码。
  • @Max: 增加 1 就足够了。但你确实有道理。它已被修复。
  • @npinti:我宁愿将它增加字符串的长度,否则它会多次检查相同的符号。想象一下,如果match 字符串的长度为 1000 个符号,那么每次迭代都必须浪费 1000 个 cpu 周期来重新比较已经完成的操作。
【解决方案3】:

试试这个:

String test = "The The The the the the";
System.out.println(test.split("The").length);

【讨论】:

  • 为什么返回长度+1?例如test.split("blah").length = 1
  • 感谢您的评论:原因是这个调用实际上使用提供的分隔符(在我们的例子中是这个词)分割字符串,所以有 #of 出现的分隔符 + 1 个部分
  • 查看我的已修复的拆分答案。
  • 由于String.split 的怪异行为,这不一定有效。 String test = "The The The the the theTheTheThe"; System.out.println(test.split("The").length); 打印出4,这肯定不是正确答案。 String.split 在尾随分隔符上有奇怪的行为,如果您在搜索字符串的末尾出现搜索字符串,这将使其不起作用。
【解决方案4】:

您可以使用 s.indexOf("The", index);,如果它返回某个索引,则增加 countindex > 也让它成为一个循环,直到找不到索引。

注意:最初 index 的值为 0

【讨论】:

    【解决方案5】:

    简单地拆分要统计的单词上的字符串。

     String text = "the the water the the";
     System.out.println(text.split("the", -1).length -1);
    

    另外,如果你当前使用的是 apache commons lang,你可以使用 StringUtils 中的 count 函数

    String text = "the the water the the";
    int count = StringUtils.countMatches(text, "the");
    System.out.println("count is " + count);
    

    但是,不要只为那个有点矫枉过正的功能引入它:)

    【讨论】:

    • 注意 -1 否则你会在拆分时得到不正确的结果
    【解决方案6】:
    String s = "The The The The The sdfadsfdas";
    
    List<String> list = Arrays.asList(s.split(" "));
    
    Set<String> unique = new HashSet<String>(list);
    for (String key : unique) {
        System.out.println(key + ": " + Collections.frequency(list, key));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多