program to find count of each character in String and print them in java


In this core java programming tutorial we will write a program to find count of each character in String and print them in java - String may consist of repeating characters in java.



Example 1 in java -
inputString is : This is it
Output is : T1h1i3s2 2t1
Example 2 in java -
inputString is : javaMadeSoEasy.com
Output is : j1a4v1M1d1e1S1o2E1s1y1.1c1m1
Example 3 in java -
inputString is : javamadesoeasy
Output is : j1a4v1m1d1e2s2o1y1

Example/ Program  - Find count of each character in String and print them in java-
/**
* @author AnkitMittal
*/
public class  CharacterCountInStringAndPrintExample {
  
   public static void main(String[] args) {
      String inputString="javamadesoeasy";
       System.out.println("inputString is : "+inputString);
       System.out.print("Output is : ");
       characterCount(inputString);
   }
  
   /**
    * Method calculates count of all characters in inputString.
    */
   public static void characterCount(String inputString){
     
      char[] inputAr=inputString.toCharArray();
      int count=0,arLength;
     
       arLength=inputAr.length;
       for(int x=0; x<arLength; x++){
        char ch=inputAr[x];
        for(int y=x+1; y<arLength; y++){
            if(inputAr[y]==ch){          //if we have find same character again in string
                for(int z=y; z< arLength-1; z++)   //shift characters left.
                inputAr[z]=inputAr[z+1];
                arLength--;   //as characters have been reduce arLength.
                y=x;   //done to tackle case if occurrence of character is more than once in string.
            }
        }
       }
      
       /*
     * Till this point of program, inputAr's first arLength number of elements are unique.
     */
      
       for(int x=0;x<arLength;x++){
          count=0;
       
          for(int y=0; y<inputAr.length; y++){
            if(inputAr[x]==inputString.charAt(y))
            count++;
        }
        System.out.print(inputAr[x]+""+count+"");
       
       }
      
      
   }
  
}
/*OUTPUT
inputString is : This is it
Output is : T1h1i3s2 2t1
*/
/*
inputString is : javaMadeSoEasy.com
Output is : j1a4v1M1d1e1S1o2E1s1y1.1c1m1
*/
/*
inputString is : javamadesoeasy
Output is : j1a4v1m1d1e2s2o1y1
*/


So in this core java programming tutorial we learned how to write a program to find count of each character in String and print them in java - String may consist of repeating characters in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.




RELATED LINKS>


>Pattern/Pyramid generating program in java










eEdit
Must read for you :