[英]Search string to find substring multiple times in Java
我有一个字符串,那么如何检查字符串中找到特定子字符串的次数?
例如,
String1 = "The fox and the hound"
,我想知道"the"
这个词出现了多少次。
我的想法是因为“the”的长度为3,我可以检查字符串中每组三个字符,但我希望有一种更有效的方法。
您可以使用StringUtils
计算如下:
String string = "The fox and the hound".toLowerCase(); // to lower
int count = StringUtils.countMatches(string, "the"); // count is 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.