Search code examples
javastringtext-parsingrepeat

Get all characters from a string with their number


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.


Solution

  • 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.