Java 统计字符串出现次数的方法
在Java中,统计字符串中某个子串出现的次数有几种常见方法,以下是几种实现方式:
方法1:使用String的indexOf方法
public static int countSubstring(String mainStr, String subStr) {
int count = 0;
int index = 0;
while ((index = mainStr.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
public static void main(String[] args) {
String str = "hello world, hello java, hello programming";
String sub = "hello";
System.out.println("出现次数: " + countSubstring(str, sub)); // 输出: 3
}
方法2:使用正则表达式
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public static int countSubstringRegex(String mainStr, String subStr) {
Pattern pattern = Pattern.compile(Pattern.quote(subStr));
Matcher matcher = pattern.matcher(mainStr);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public static void main(String[] args) {
String str = "hello world, hello java, hello programming";
String sub = "hello";
System.out.println("出现次数: " + countSubstringRegex(str, sub)); // 输出: 3
}
方法3:使用Java 8的Stream API
import java.util.regex.Pattern;
public static long countSubstringStream(String mainStr, String subStr) {
return Pattern.compile(Pattern.quote(subStr))
.matcher(mainStr)
.results()
.count();
}
public static void main(String[] args) {
String str = "hello world, hello java, hello programming";
String sub = "hello";
System.out.println("出现次数: " + countSubstringStream(str, sub)); // 输出: 3
}
方法4:统计单词出现次数(区分大小写)
import java.util.HashMap;
import java.util.Map;
public static Map<String, Integer> countWords(String text) {
Map<String, Integer> wordCount = new HashMap<>();
String[] words = text.split("\\s+"); // 按空格分割
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
return wordCount;
}
public static void main(String[] args) {
String text = "hello world hello java hello programming";
Map<String, Integer> counts = countWords(text);
System.out.println("hello 出现次数: " + counts.get("hello")); // 输出: 3
}
注意事项
- 上述方法都是区分大小写的,如果不区分大小写,可以将字符串都转换为小写后再比较
- 对于重叠子串(如"aaa"中"aa"出现2次),方法1和正则表达式方法都能正确统计
- 方法4适合统计单词出现次数,而前三种方法适合统计任意子串
选择哪种方法取决于你的具体需求和Java版本,对于简单场景,方法1足够;对于复杂模式匹配,正则表达式方法更强大。
