我想知道如何读取一个文件,然后计算某个字符串出现的次数。计算一个字符串出现在文件中的次数
这是我的文件看起来像,它是一个.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