views:

102

answers:

3

How in Java can I get list of all characters appearing in string, with number of their appearances ? Let's say we have a string "I am really busy right now" so I should get :

i-2, a-2, r-2, m-1 and so on.

A: 

Is it homework? Without knowing it I'll assume a best-effort answer.

The logic behind your problem is to

  • go trought the list one character at time
  • count that character: since possible characters (excluding unicode) are just 256 you can have an array of 256 ints and count them there: in this way you won't need to search the correct counter but just increment the right index.
Jack
no I just need it for my project
terence6
+2  A: 

Just have a mapping of every character and their counts. You can get the character array of a String using String#toCharArray() and loop through it using the enhanced for loop. On every iteration, get the count from the mapping, set it if absent and then increment it with 1 and put back in map. Pretty straightforward.

Here's a basic kickoff example:

String string = "I am really busy right now";
Map<Character, Integer> characterCounts = new HashMap<Character, Integer>();
for (char character : string.toCharArray()) {
    Integer characterCount = characterCounts.get(character);
    if (characterCount == null) {
        characterCount = 0;
    }
    characterCounts.put(character, characterCount + 1);
}

To learn more about maps, check the Sun tutorial on the subject.


You commented that it's "for a project", but it's however a typical homework question because it's pretty basic and covered in the first chapters of a decent Java book/tutorial. If you're new to Java, I suggest to get yourself through the Sun Trails Covering the Basics.

BalusC
A Character is not a character anymore, unfortunately.
GregS
A: 

I'm not sure of your exact needs but it seems you want to count occurrences regardless of the case, maybe also ignore characters such as whitespace, etc. So you might want something like this:

String initial = "I   am really   busy  right now";

String cleaned = initial.replaceAll("\\s", "") //remove all whitespace characters
        .toLowerCase(); // lower all characters

Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char character : cleaned.toCharArray()) {
    Integer count = map.get(character);
    count = (count!=null) ? count + 1 : 1;
    map.put(character, count);
}

for (Map.Entry<Character, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

Tweak the regex to meet your exact requirements (to skip punctuation, etc).

Pascal Thivent