Find specific word in text file and count it

2020-03-02 03:17发布

someone can help me with code? How to search in text file any word and count how many it were repeated?

For example test.txt:

hi
hola
hey
hi
bye
hoola
hi

And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"

I hope you understood what I want, thank you for answers.

13条回答
Rolldiameter
2楼-- · 2020-03-02 03:44
package File1;

import java.io.BufferedReader;
import java.io.FileReader;

public class CountLineWordsDuplicateWords {

public static void main(String[] args) {
    FileReader fr = null;
    BufferedReader br =null;

    String [] stringArray;
    int counLine = 0;
    int arrayLength ;
    String s="";
    String stringLine="";
    try{
        fr = new FileReader("F:/Line.txt");
        br = new BufferedReader(fr);
        while((s = br.readLine()) != null){
            stringLine = stringLine + s;
            stringLine = stringLine + " ";/*Add space*/
            counLine ++;
        }
        System.out.println(stringLine);

        stringArray = stringLine.split(" ");
        arrayLength = stringArray.length;
                     System.out.println("The number of Words is "+arrayLength);
        /*Duplicate String count code */
        for (int i = 0; i < arrayLength; i++) {
            int c = 1 ;
            for (int j = i+1; j < arrayLength; j++) {
                if(stringArray[i].equalsIgnoreCase(stringArray[j])){
                    c++;
                    for (int j2 = j; j2 < arrayLength; j2++) {
                        stringArray[j2] = stringArray[j2+1];
                        arrayLength = arrayLength - 1;
                    }

                }//End of If block
            }//End of Inner for block
        System.out.println("The "+stringArray[i]+" present "+c+" times .");
        }//End of Outer for block
        System.out.println("The number of Line is "+counLine);
        System.out.println();
        fr.close();
        br.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
}//End of main() method 
}//End of class CountLineWordsDuplicateWords
查看更多
登录 后发表回答