搜索字符串以在 Java 中多次查找子字符串

Search string to find substring multiple times in Java

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

例如,

String1 = "The fox and the hound"

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

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

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

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);
  }

你可以用StringUtils这样算:

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

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