count frequency of characters in string code example

Example 1: java count frequency of characters in a string

public class Frequency   
{  
     public static void main(String[] args) {  
        String str = "picture perfect";  
        int[] freq = new int[str.length()];  
        int i, j;  
          
        //Converts given string into character array  
        char string[] = str.toCharArray();  
          
        for(i = 0; i <str.length(); i++) {  
            freq[i] = 1;  
            for(j = i+1; j <str.length(); j++) {  
                if(string[i] == string[j]) {  
                    freq[i]++;             
                    //Set string[j] to 0 to avoid printing visited character  
                    string[j] = '0';  
                }  
            }  
        }  
        //Displays the each character and their corresponding frequency  
        System.out.println("Characters and their corresponding frequencies");  
        for(i = 0; i <freq.length; i++) {  
            if(string[i] != ' ' && string[i] != '0')  
                System.out.println(string[i] + "-" + freq[i]);  
        }  
    }  
}

Example 2: Write a c program to count the different types of characters in given string.

#include<stdio.h>
   #include<string.h> 
	void main()    {
   		char arr[]="askjdfbajksdfkasdfhjkasdfh";
   		char x;
   		int l=strlen(arr);
   		int i=0,j;
   		int c=0,var=0;
   		for(j=97;j<=122;j++) {     //a=97,z=122
   		//c=j;           
   			for(i=0;i<l-1;i++) {
   	       		if(arr[i]==j) {
   	         		c++; 
   	       		} 
   	     	} 
   	  		if(c>0) {
   	    		var++;
   	    		printf("No. of Occurence of %c ::%d\n",j,c); 
   	  		}
   	  		c=0; 
   		} 
   	  	printf("No. of type of characters:%d\n",var);   
   	}

Example 3: frequency of letters in english java

Map<Character, Long> frequency =
            str.chars()
               .mapToObj(c -> (char)c)
               .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Tags:

C Example