统计txt文件中出现的某个字符串次数


  

代码:

参考:https://www.cnblogs.com/mlan/p/7811382.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class strCounts {
//主函数
public static int process(File file, String key){
FileInputStream fis = null;
int sum = 0;
try{
fis = new FileInputStream(file);
int len = 0;
byte[] buf = new byte[1024];
String str = null;
while((len = fis.read(buf)) !=-1){
str = new String(buf, 0, len,"GBK");
int count = getKeyStringCount(str,key);
sum = sum + count;
}

}catch(FileNotFoundException e){
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return sum;
}

// 统计主串str中子串key出现的次数(注意,这不同于模式匹配算法!)

1
2
3
4
5
6
7
8
9
10
public 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+"次");
}
}

---------------- The End ----------------
0%