如何使用文件计算字母表中每个字符的出现次数

时间:2014-11-28 19:47:19

标签: java

我想知道如何启动一个读取文件的程序,并逐行计算字母表中每个字母的出现次数。我知道我想使用一个包含字母的数组,但是我不知道如何阅读每一行,然后按字母顺序打印出计数。

4 个答案:

答案 0 :(得分:2)

  BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
    int ch;
    char charToSearch='a';
    int counter=0;
    while((ch=reader.read()) != -1) {
        if(charToSearch == (char)ch) {
            counter++;
        }
    };
    reader.close();

    System.out.println(counter);

参考:Counting letter occurrence

答案 1 :(得分:0)

试试这个

public void countOccurence() {
 BufferedReader reader
                     = new BufferedReader(new FileReader("somefile.txt"));

String text = "";
while((ch=reader.read()) != -1) {
       text = text +ch;
    };
    reader.close();


 for(Character a :"abcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
    {

         int ch;
         char charToSearch=a;
         int counter=0;
         for(Character b : text.toCharArray())
            {
              if(charToSearch == (char)b) {
                counter++;
                  }
            }

    System.out.pritln("Character: " +charToSearch+ " occurs " + counter 
    + " times.");

         }
    }

如果适合你,请标记为:)

答案 2 :(得分:0)

    public void count() throws Exception {
        int[] array = new int[26];
        BufferedReader br = new BufferedReader(new FileReader("file.txt"));
        int ch;
        while((ch = br.read()) != -1) {
            if (ch > 64 && ch < 97) // Upper case letters
                ch += 32; // to get the ascii value of the letter in lowercase
            if(-1 < ch-97 && ch-97 < 26)
                array[ch-97] += 1;
        }
        br.close();
        int i = 0;
        for (char chr = 'a'; chr <= 'z'; chr++) {
            System.out.printf("%s --> %d\n", chr, array[i]);
            i++;
        }
    }

答案 3 :(得分:0)

BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
int ch; 
Map<char, int> charCount = new Map<char, int>();
while((ch=reader.read()) != -1) {
    if(charCount.contains(ch)) {
        charCount.put(ch, charCount.get(ch)++);
    } else {
        charCount.put(ch, 1);
    }
}
reader.close();

for(String key: charCount.keySet())
    System.out.println(key + " - " + charCount.get(key));
System.out.println();

这将为文件中的每个字符保留一个计数器。如果您想将此设置限制为字母表,可以通过在将ch放入charCount之前检查字母是否为{{1}}来轻松完成。