0

I have trouble reading the char part of a text file and making each char have a value that is the number of that char in the file.

For example:

i'm eating

should be:

i = 2
m = 1
e = 1
a = 1
t = 1
n = 1
g = 1

Can anyone help me?

waka
  • 3,362
  • 9
  • 35
  • 54
  • `Map ? or a simple `int[]` if you have a specific set of character (letters only for example could be done with (int[26]). Now try this and come back to us with something you tried. Can't say more than this. – AxelH Oct 27 '17 at 10:07
  • Have you tried anything yet? Show us some code? – Ridcully Oct 27 '17 at 11:58
  • Possible duplicate of https://stackoverflow.com/questions/275944/java-how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string – Dries De Rydt Oct 27 '17 at 12:22

1 Answers1

0

Java char type is a 16-bit integer (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html), so a relatively small array can store the counters:

int statistics[]=new int[65536];
int onechar;
while(-1!=(onechar=br.read())){
    statistics[onechar]++;
}

for(int i=' ';i<statistics.length;i++){
    if(statistics[i]>0){
        System.out.println(String.format("%c: %d",i,statistics[i]));
    }
}

Where br is the BufferedReader

tevemadar
  • 12,389
  • 3
  • 21
  • 49