java 计算字符串在文件中出现的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11066552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:39:21  来源:igfitidea点击:

Count the amount of times a string appears in a file

javastringfilereader

提问by Zomby

I'm trying to figure out how I would read a file, and then count the amount of times a certain string appears.

我试图弄清楚我将如何读取文件,然后计算某个字符串出现的次数。

This is what my file looks like, it's a .txt:

这是我的文件的样子,它是一个 .txt:

    Test
    Test
    Test
    Test

I want the method to then return how many times it is in the file. Any idea's on how I could go about doing this? I mainly need help with the first part. So if I was searching for the string "Test" I would want it to return 4.

我希望该方法返回它在文件中的次数。关于我如何去做这件事的任何想法?我主要需要第一部分的帮助。因此,如果我正在搜索字符串“Test”,我希望它返回 4。

Thanks in advanced! Hope I gave enough info!

先谢谢了!希望我提供了足够的信息!

采纳答案by GETah

Here you are:

这个给你:

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;
}

Usage: int count = countStringInFile("SomeWordToLookFor", "FileName");

用法: int count = countStringInFile("SomeWordToLookFor", "FileName");

回答by Austin

Add this method to your class, pass your FileInputStream to it, and it should return the number of words in a file. Keep in mind, this is case sensitive.

将此方法添加到您的类中,将您的 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;
}

Just wrote that now, and it's untested, so let me know if it works. Also, make sure that you understand what I did if this is a homework question.

现在才写出来,它未经测试,所以让我知道它是否有效。另外,如果这是一个家庭作业问题,请确保您理解我所做的。

回答by John D

If you have got to the point of reading in each file into a string I would suggest looking at the String method split.

如果您已经到了将每个文件读入字符串的程度,我建议您查看 String 方法 split。

Give it the string code 'Test' and it will return an array of type string - count the number of elements per line. Sum them up to get your total occurrence.

给它字符串代码“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){
        }
    }
}

回答by ΦXoc? ? Пepeúpa ツ

I would do this:

我会这样做:

  1. open and read the file line by line,
  2. check how oft a line contains the given word...
  3. increase a global counter for that..
  1. 逐行打开并读取文件,
  2. 检查一行包含给定单词的频率...
  3. 为此增加一个全局计数器..


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 ");
}