Slip No 10 Q A

Q.Write a java program to count the frequency of each character in a given string. [15 M]

import java.util.Scanner;

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

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        // Convert string to character array
        char[] ch = str.toCharArray();

        System.out.println("\nCharacter Frequencies:");

        for(int i = 0; i < ch.length; i++) {
            int count = 1;

            if(ch[i] == '0')   // marker for counted characters
                continue;

            for(int j = i + 1; j < ch.length; j++) {
                if(ch[i] == ch[j]) {
                    count++;
                    ch[j] = '0';   // mark as counted
                }
            }

            if(ch[i] != '0')
                System.out.println(ch[i] + " : " + count);
        }

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top