Rasmus
Rasmus

Reputation: 241

Count character occurrences in a file

I want a short and efficient code of counting the occurence of different characters and numbers in a textfile. This one is only for one character.

Is there a way to this without giving every single character and number a charToSearch variable? Also without having an enormous ugly if statement.

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

Upvotes: 1

Views: 208

Answers (2)

Ensar Hatipoglu
Ensar Hatipoglu

Reputation: 193

You can use a hashmap:

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

Upvotes: 2

Nitesh
Nitesh

Reputation: 3903

Try this.

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

             }
        }

Upvotes: 1

Related Questions