Sunday, September 16, 2018

Java Program to Count each Characters in a String

public class CountEachChar {
           
 public static void main(String[] args) {
           

                        String str="Java is a fun language";
                       
                        //Creating a HashMap containing char as a key and occurrences as  a value
                        String str1=str.toLowerCase();
                        Map<Character, Integer> charCountMap = new HashMap<Character, Integer>();
                       
                        //Converting given string to char array
                        char[] strArray = str1.toCharArray();
                       
                        //checking each char of strArray
                       
                        for(char c: strArray){
                                   
                                    if(charCountMap.containsKey(c)){
                                               
                                                //If char is present in charCountMap, incrementing it's count by 1
                                               
                                                charCountMap.put(c, charCountMap.get(c)+1);
                                                           
                                    }
                                    else{
                                                //If char is not present in charCountMap,
                //putting this char to charCountMap with 1 as it's value
                                                charCountMap.put(c, 1);
                                               
                                    }
                                   
                        }
                       
                       
                        System.out.println(charCountMap);

                        }
  }




 Output:  { =4, a=5, s=1, u=2, e=1, v=1, f=1, g=2, i=1, j=1, l=1, n=2}

1 comment:

  1. You completed a few fine points there. I did a search on the subject and found nearly all persons will go along with with your blog. charactercount.org

    ReplyDelete