Java 统计字符串中字符串个数
在Java中,统计字符串中某个子字符串出现的次数有几种常见方法,以下是几种实现方式:

方法1:使用String类的indexOf()方法
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
方法2:使用正则表达式
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public static int countSubstringRegex(String str, String subStr) {
Pattern pattern = Pattern.compile(Pattern.quote(subStr));
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
方法3:使用Java 8 Stream API
public static int countSubstringStream(String str, String subStr) {
return (int) IntStream.range(0, str.length() - subStr.length() + 1)
.filter(i -> str.startsWith(subStr, i))
.count();
}
方法4:使用Apache Commons Lang库
如果你可以使用第三方库,Apache Commons Lang提供了更简洁的方法:
import org.apache.commons.lang3.StringUtils;
public static int countSubstringApache(String str, String subStr) {
return StringUtils.countMatches(str, subStr);
}
完整示例
public class StringCounter {
public static void main(String[] args) {
String str = "hello world, hello java, hello programming";
String subStr = "hello";
// 方法1
System.out.println("方法1结果: " + countSubstring(str, subStr));
// 方法2
System.out.println("方法2结果: " + countSubstringRegex(str, subStr));
// 方法3
System.out.println("方法3结果: " + countSubstringStream(str, subStr));
// 方法4(需要添加Apache Commons Lang依赖)
// System.out.println("方法4结果: " + countSubstringApache(str, subStr));
}
// 这里放置上面的方法实现...
}
注意事项
- 上述方法都区分大小写,如果需要不区分大小写,可以在比较前将字符串都转换为小写或大写
- 对于重叠的子字符串,方法1和方法3会忽略重叠部分,而方法2会计算重叠部分
- 如果子字符串为空,不同方法可能有不同的行为,需要根据实际需求处理
选择哪种方法取决于你的具体需求、性能考虑以及是否可以使用第三方库。

