輸入一個(gè)文件名,統(tǒng)計(jì)文件中字符串的出現(xiàn)次數(shù)
代碼
/**
* 統(tǒng)計(jì)給定文件中給定字符串的出現(xiàn)次數(shù)
* @param filename 文件名
* @param word 字符串
* @return 字符串在文件中出現(xiàn)的次數(shù)
*/
public static int countWordInFile(String filename, String word) {
int counter = 0;
try (FileReader fr = new FileReader(filename)) {
try (BufferedReader br = new BufferedReader(fr)) {
String line = null;
while ((line = br.readLine()) != null) {
int index = -1;
while (line.length() >= word.length() && (index =
line.indexOf(word)) >= 0) {
counter++;
line = line.substring(index + word.length());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return counter;
}
學(xué)習(xí)讓我快樂,工作讓我快樂。學(xué)習(xí)和工作都是為了更好的生活!

浙公網(wǎng)安備 33010602011771號(hào)