我想知道如何讀取一個文件,然後計算某個字符串出現的次數。計算一個字符串出現在文件中的次數
這是我的文件看起來像,它是一個.TXT:
Test
Test
Test
Test
我想要的方法,然後返回它在文件中有多少次。任何想法都是關於如何去做這件事的?我主要需要第一部分的幫助。所以,如果我搜索字符串「測試」,我想它會返回4.
感謝先進!希望我給了足夠的信息!
我想知道如何讀取一個文件,然後計算某個字符串出現的次數。計算一個字符串出現在文件中的次數
這是我的文件看起來像,它是一個.TXT:
Test
Test
Test
Test
我想要的方法,然後返回它在文件中有多少次。任何想法都是關於如何去做這件事的?我主要需要第一部分的幫助。所以,如果我搜索字符串「測試」,我想它會返回4.
感謝先進!希望我給了足夠的信息!
給你:
public int countStringInFile(String stringToLookFor, String fileName){
int count = 0;
try{
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
int startIndex = strLine.indexOf(stringToLookFor);
while (startIndex != -1) {
count++;
startIndex = base.indexOf(stringToLookFor,
startIndex +stringToLookFor.length());
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return count;
}
用法:int count = countStringInFile("SomeWordToLookFor", "FileName");
將此方法添加到您的類中,將FileInputStream傳遞給它,並返回文件中的單詞數。請記住,這是區分大小寫的。
public int countWord(String word, FileInputStream fis) {
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String readLine = "";
int count = 0;
while((readLine = in.readLine()) != null) {
String words = readLine.split(" ");
for(String s : words) {
if(s.equals(word)) count++;
}
return count;
}
剛剛寫到現在,它沒有經過測試,所以讓我知道它是否有效。另外,如果這是一個家庭作業問題,請確保你明白我的所作所爲。
如果你不得不讀每個文件轉換成字符串,我建議看字符串的方法分割點。
給它的字符串代碼'Test',它將返回一個字符串類型的數組 - 計算每行元素的數量。總結他們以獲得您的總髮生次數。
import java.io.*;
public class StringCount {
public static void main(String args[]) throws Exception{
String testString = "Test";
String filePath = "Test.txt";
String strLine;
int numRead=0;
try {
FileInputStream fstream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
strLine = strLine + " ";
String [] strArry = strLine.split(testString);
if (strArry.length > 1) {
numRead = numRead + strArry.length - 1;
}
else {
if (strLine == testString) {
numRead++;
}
}
}
in.close();
System.out.println(testString + " was found " + numRead + " times.");
}catch (Exception e){
}
}
}
每次只返回1個。當「測試」被寫了6次。任何想法爲什麼? – Zomby
你能提供你的測試文件嗎?所有我對它的測試都正確返回,所以很奇怪我錯過了什麼用例。 –
我這樣做:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String word = sc.next();
String line = in.readLine();
int count = 0;
do {
count += (line.length() - line.replace(word, "").length())/word.length();
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurrences of " + word + " in ");
}
到目前爲止你做了什麼?這看起來像作業 –
我所做的一切都是讓我的程序取得一個字符串(玩家的名字),然後每次將它寫入一個新行的文件中。這不是家庭作業,這是我的遊戲的警告/禁止系統 – Zomby