简体   繁体   English

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

[英]How to count occurrence of each character in the alphabet with a file

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

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

Reference: Counting letter occurrence 参考: 盘点字母出现

try this 尝试这个

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

         }
    }

Mark as up, if it works for you :) 标记为up,如果它对您有用:)

    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++;
        }
    }
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();

This will keep a counter for EVERY character in the file. 这将为文件中的每个字符保留一个计数器。 If you want to limit this set to an alphabet, this can be done easily by checking is ch is in the alphabet before putting it in charCount . 如果要将此设置限制为字母,则可以通过在将其放入charCount之前检查ch是否存在字母来轻松charCount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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