Wednesday, 25 October 2023

Write a java program to count the frequency of each character in a given string.-Core Java Slip10

 

Write a java program to count the frequency of each character in a given string.

import java.util.HashMap;

import java.util.Map;

import java.io.*;

 

public class CharacterFrequencyCounter {

    public static void main(String[] args) {

        String inputString = "Hello, World!";

       

        // Create a HashMap to store character frequencies

        Map<Character, Integer> charFrequencyMap = new HashMap<>();

       

        // Iterate through the characters in the string

        for (char c : inputString.toCharArray()) {

            if (charFrequencyMap.containsKey(c)) {

                // Character already exists in the map, increment the count

                charFrequencyMap.put(c, charFrequencyMap.get(c) + 1);

            } else {

                // Character does not exist in the map, add it with a count of 1

                charFrequencyMap.put(c, 1);

            }

        }

       

        // Print the character frequencies

        for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) {

            System.out.println("Character: " + entry.getKey() + ", Frequency: " + entry.getValue());

        }

    }

}

Output

 

 

C:\Program Files\Java\jdk-11.0.17\bin>javac CharacterFrequencyCounter.java

C:\Program Files\Java\jdk-11.0.17\bin>java CharacterFrequencyCounter

Character:  , Frequency: 1

Character: !, Frequency: 1

Character: r, Frequency: 1

Character: d, Frequency: 1

Character: e, Frequency: 1

Character: W, Frequency: 1

Character: H, Frequency: 1

Character: l, Frequency: 3

Character: ,, Frequency: 1

Character: o, Frequency: 2