简体   繁体   中英

Count the amount of times a string appears in a file

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:

    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.

Thanks in advanced! Hope I gave enough info!

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.

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.

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

If you have got to the point of reading in each file into a string I would suggest looking at the String method 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.

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){
        }
    }
}

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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM