代码:
参考:https://www.cnblogs.com/mlan/p/7811382.html
1 | public class strCounts { |
// 统计主串str中子串key出现的次数(注意,这不同于模式匹配算法!)1
2
3
4
5
6
7
8
9
10public static int getKeyStringCount(String str, String key) {
int count = 0;
int index = 0;
//indexOf(key,index):返回指定子串的第一次出现的字符串中的索引,从指定的索引开始
while((index = str.indexOf(key,index))!=-1){
index = index + key.length();
count++;
}
return count;
}
// 测试1
2
3
4
5
6
7 public static void main(String[] args) {
File file = new File("D:/test.txt");
String key = "aa";
int sum = process(file, key);
System.out.println("文件中字符串"+key+"出现的次数为:"+sum+"次");
}
}