Print total number occurrences each character String

Print total number occurrences each character String

Write a java method that will take a String argument and print total number of occurrences of each character in the input string.

For example: For a “hello world” input, the expected output is below

h – 1
e – 1
l – 3
o – 2
w – 1
r – 1
d – 1

package com.javahonk;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class CheckOccuranceOfChar {

    public static void main(String[] args) {
        String str = "hello world";
        getCount(str);

    }

    public static void getCount(String name) {
        
        Map<Character, Integer> names = 
                new LinkedHashMap<Character, Integer>();
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            Integer count = names.get(c);
            if (count == null) {
                count = 0;
            }
            names.put(c, count + 1);
        }
        Set<Character> a = names.keySet();
        for (Character t : a) {
            if (!t.equals(' '))
                System.out.println(t + " Ocurred " 
            + names.get(t) + " times");

        }
    }

}

Output:
Print total number occurrences each character String

Leave a Reply

Your email address will not be published. Required fields are marked *