本文介绍了计算字符串在文件中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

    Test
    Test
    Test
    Test

我希望该方法返回文件中的次数.关于如何执行此操作有任何想法吗?我主要需要第一部分的帮助.因此,如果我要搜索字符串"Test",我希望它返回4.

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.

非常感谢!希望我能提供足够的信息!

Thanks in advanced! Hope I gave enough info!

推荐答案

您在这里:

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

这篇关于计算字符串在文件中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 14:08