【问题标题】:Search string to find substring multiple times in Java在Java中搜索字符串以多次查找子字符串
【发布时间】:2015-03-20 16:12:41
【问题描述】:

我有一个字符串,那么如何检查在字符串中找到特定子字符串的次数?

例如,

String1 = "The fox and the hound"

,我想知道"the"这个词出现了多少次。

我的想法是,由于“the”的长度为 3,我可以检查字符串中的每一组三个字符,但我希望有一种更有效的方法。

【问题讨论】:

  • API doc中参考indexOf(String)indexOf(String, int)

标签: java string substring


【解决方案1】:

你可以使用StringUtils这样计数:

String string = "The fox and the hound".toLowerCase(); // to lower

int count = StringUtils.countMatches(string, "the"); // count is 2

【讨论】:

    【解决方案2】:

    这里有一个正则表达式的解决方案:

    import java.util.regex.*;
    
    public class RegexToCountWords {
      public static final String SAMPLE_STRING = "The fox and the hound";
      public static final String SEARCH_STRING = "the";
    
      public static void main(String[] args) {
        // pattern to compare \\b matches word boundaries
        Pattern pattern = Pattern.compile("\\b" + SEARCH_STRING + "\\b");
        Matcher matcher = pattern.matcher(SAMPLE_STRING.toLowerCase());
        //matcher.find() checks for all occurrances
        int count = 0;
        while (matcher.find()) {
          count++;
        }
        System.out.println("Sample String : " + SAMPLE_STRING);
        System.out.println("Number of matching strings : " + count);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2019-10-06
      • 2012-04-10
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多