Get all characters from a string with their number

How in Java can I get a list of all the characters that appear in a string, with the number of occurrences? Let's say we have the line "I'm really busy now", so I should get:

i-2, a-2, r-2, m-1, etc.

+3
source share
3 answers

Just have a display of each character and their score. You can get an array of characters Stringwith String#toCharArray()and pass it through improved for loop . At each iteration, get a counter from the display, set it if it is missing, then increase it by 1 and return it to the map. Pretty simple.

Here is an example of the main launch:

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

, Sun .


, " ", , , , / Java. Java, Sun Trails Covering the Basics.

+4

? , .

  • : ( unicode) 256, 256 int : , .
0

I'm not sure about your specific needs, but it seems like you want to count cases regardless of the case, maybe also ignore characters like spaces, etc. Therefore, you may need 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());
}

Adjust the regex to suit your exact requirements (to skip punctuation, etc.).

0
source

Source: https://habr.com/ru/post/1747790/


All Articles