Answers for "java program to count the frequency of each character in a string"

0

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]);  
        }  
    }  
}
Posted by: Guest on June-07-2020
0

string frequency of characters in java

String str = "AAAABBCCDD"; // A4B2C2D2
        String result1 = "";
        String nonDup = "";

        for(int i=0; i < str.length(); i++)
            if(!nonDup.contains(""+str.charAt(i)))
                nonDup+= ""+str.charAt(i);

        for( int j=0;j < nonDup.length(); j++) {
            int count = 0;
            for(int i=0; i < str.length(); i++) {
                if(str.charAt(i) == nonDup.charAt(j))
                    count++;
            }
            result1 +=nonDup.charAt(j)+"" + count;
        }
        System.out.println(result1); // A4B2C2D2
Posted by: Guest on June-09-2021

Code answers related to "java program to count the frequency of each character in a string"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language