Count occurrences of character in String java program code with example

The common technical interview question in java is to count the occurrence of  a specific word in the string but what if interviewer ask to count the total number of times each alphabet appears in the string . That the question, whose logic you need to think at that point of time and sadly there is no  built in  java method to give you the direct answer by passing the input string .

Read Also :    Count number of  words in the String with Example

So in order to be prepared for such type of questions I have shared the program code below .

Input string  :       "Alive is awesome"

Output           :      A=1,l=1,i=2,v=1,e=3, =2,s=2,a=1,w=1,o=1,m=1
                                                                               

Note :  The result is case sensitive , it means uppercase and lowercase alphabet are treated as different.
for example , Please see above  the alphabet which is texted in Red

Read Also :    Find first Non-Repeated Character in the String


1. Pseudo code/Logic for Count occurrences of Character in String in Java

I will use HashMap to count occurrences of Character in String in java. It will have Character as key and its count occurrences as value. First we will convert the given string into char array.Then , we will traverse char array and increment its value by 1 for each Character present in the input string.



public class EachCharacterCountInString
{ 
 public static void main(String[] args)
{
characterCount("Alive is Awesome");

characterCount("Java Hungry");

characterCount("USA has 50 states");
}
 
 static void characterCount(String inputString)
{
//Creating a HashMap, key :Character value : occurrences as Integer

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

//Converting inputString to char array

char[] charArray = inputString.toCharArray();

//traversal of each Character of charArray

for (char c : charArray)
{
if(eachCharCountMap.containsKey(c))
{
//If char is present in eachCharCountMap, increment count by 1

eachCharCountMap.put(c, eachCharCountMap.get(c)+1);
}
else
{
//If char is not present in eachCharCountMap,
//Putting this char to eachCharCountMap with 1 as it's initial value

eachCharCountMap.put(c, 1);
}
}

//Showing the eachCharCountMap

System.out.println(eachCharCountMap);
}

}

Output:

{ =2, A=1, a=1, s=2, e=3, v=1, w=1, i=2, l=1, m=1, o=1}
{ =1, a=2, r=1, u=1, v=1, g=1, H=1, y=1, J=1, n=1}
{ =3, 0=1, A=1, a=2, S=1, s=3, t=2, U=1, 5=1, e=1, h=1}





2. Pseudo code/Logic  for Count occurrences of Character in String in Java (Without using HashMap)


   *  We store the input string in an character array (below z) .(We want to create a character array z without                                                                                                any duplicate alphabet )
   *  We start traversing the string in array z[i].
           for i=0 to i<z.length

               Store the character at index i that is z[i] in temporary variable ch
                               for  z[i+1] to z.length  
                                           if  ch is equals to the any element of the rest of the array characters          
                                               then   move the  cursor  to next index and reduce the length of the string by 1
                                               set s[k]=s[k+1] // deleting the alphabet which is already in array z
                                               set j=i    

    *  Create a new array of integers to store the count of  total number of appearances of alphabets   in the           string     (below t)

    *  Compare every element of string s with   the every element of character array z
                      if both are equal then
                             increase count by 1
         Add the final count value to the array t (which is used to store the final count of  total number of                                                                                occurrences of the alphabet in the string )

    *  Print  the count of the alphabet                                  


count total number of times each alphabet appears in the string java program

























Code :



public class  AlphabetFrequencyString {


static int i,j,k,c=0,w;

static char m; //we can only define static for variables and fns not for arrays

public static void main(String[] args) {
System.out.println("Input string is : ");
System.out.println("Alive is awesome");
System.out.println("");
System.out.println("");
System.out.println("Output :");
frequencycount("Alive is awesome");
}


static void frequencycount(String s)

{

char[] z=new char[s.length()];
for(w=0;w<s.length();w++)
z[w]=s.charAt(w);
for(i=0;i<w;i++)
{
char ch=z[i];
for(j=i+1;j<w;j++)
{
if(z[j]==ch)
{
for(k=j;k<(w-1);k++)
z[k]=z[k+1];
w--;
j=i;
}
}
}

int[] t=new int[w];
for(i=0;i<w;i++)
{
for(j=0,c=0;j<s.length();j++)
{
if(z[i]==s.charAt(j))
c++;
}
t[i]=c ;
System.out.print(z[i]+"="+c+",");
}
}

}

Please mention in the comments if you have your own code on count occurrences of character in String in java.

0 Comments