java 代碼
/**
* 讀取文本文件(path),獲取某字符串(str)出現的次數
* @param path 指定一個文件路徑(不能爲空)
* @param str 目標字符串
* @return 出現次數
*/
private static int getStrCount(String path, String str){
int count = 0;
try {
// 讀取文件
List<String> strings = Files.readAllLines(Paths.get(path));
for (String string : strings) {
// 當存在該字符串時,進行計數並且將原字符串(出現的第一個位置)替換爲空字符串
while(string.contains(str)){
count++;
string = string.replaceFirst(str, "");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
測試
在對應位置創建文本文件(1.txt):
hello world hello
hello
world
ni hao shuai
shi bu shi a
hello
short
在 main 方法中執行以下語句:
含義是查找 hello 這個字符串在文本文件 1.txt 中出現的次數。
System.out.println(getStrCount("D:\\ideaProjects\\java-demo\\target\\classes\\files\\1.txt", "hello"));