A char
is a 16-bit unsigned value, and if you cast it to an int
, then you'll get a value between 0 and 65535. That means that you can just use an array to store your characters:
int[] charCounts = new int[65536];
and then when you want to record an occurrence of char c
:
charCounts[(int) c]++;
When you want to read off the counts:
for (int i=0; i<65536; i++)
if (charCounts[i]>0)
System.out.println((char)(i)+": "+charCounts[i]);
There is nothing to stop you doing it with a HashMap<Character,Integer>
if you want to do it as an exercise, though it's more heavyweight than it needs to be for this:
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
and when you want to record the occurrence of char c
:
if (!map.containsKey(c))
map.put(c,1);
else
map.put(c,map.get(c)+1);
and when you want to read off:
for (Map.Entry<Character,Integer> entry: map.entrySet())
System.out.println(entry.getKey()+": "+entry.getValue());
Note that for all of this I've assumed you're dealing only with printable characters. If not, you'll want to do something about that when you print them out.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…