0 votes
in JAVA by
How to count the number of occurrences of a character in a string in java?

1 Answer

0 votes
by
How to count the number of occurrences of a character in a string in java?

"import java.util.HashMap;

 

public class EachCharCountInString

{

    private static void characterCount(String inputString)

    {

        //Creating a HashMap containing char as a key and occurrences as a value

  

        HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();

  

        //Converting given string to char array

  

        char[] strArray = inputString.toCharArray();

  

        //checking each char of strArray

  

        for (char c : strArray)

        {

            if(charCountMap.containsKey(c))

            {

                //If char 'c' is present in charCountMap, incrementing it's count by 1

  

                charCountMap.put(c, charCountMap.get(c)+1);

            }

            else

            {

                //If char 'c' is not present in charCountMap,

                //putting 'c' into charCountMap with 1 as it's value

  

                charCountMap.put(c, 1);

            }

        }

         

        //Printing inputString and charCountMap

  

        System.out.println(inputString+"" : ""+charCountMap);

    }

  

    public static void main(String[] args)

    {

       characterCount(""Java J2EE Java JSP J2EE"");

  

       characterCount(""All Is Well"");

  

       characterCount(""Done And Gone"");

    }

}"

Related questions

0 votes
asked Mar 16, 2021 in JAVA by Robindeniel
0 votes
asked Oct 24, 2020 in JAVA by sharadyadav1986
...