计算文件中的字符出现次数

时间:2014-11-25 19:09:53

标签: java count

我想要一个简短有效的代码来计算文本文件中不同字符和数字的出现次数。这个只适用于一个角色。

有没有办法解决这个问题而不给每个字符和数字一个charToSearch变量?也没有一个巨大的丑陋if声明。

    public void countOccurence() {
    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.pritln("Character: " + charToSearch + " occurs " + counter + " times.");

    }

2 个答案:

答案 0 :(得分:2)

您可以使用散列图:

Map<Character, Integer> charMap = new HashMap<Character, Integer>();
while((ch=reader.read()) != -1) {
  char key = (char)ch;
  if(charMap.containsKey(key)) {
    int value = charMap.get(key);
    charMap.put(key, value + 1);
  } else {
     charMap.put(key,1);
  }
}

答案 1 :(得分:1)

试试这个。

public void countOccurence() {

   for(Character ch :"abcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
        {
             BufferedReader reader
                         = new BufferedReader(new FileReader("somefile.txt"));
             int ch;
             char charToSearch=ch;
             int counter=0;
             while((ch=reader.read()) != -1) {
                   if(charToSearch == (char)ch) {
              counter++;
          }
        };
        reader.close();
        System.out.pritln("Character: " + charToSearch + " occurs " + counter 
        + " times.");

             }
        }