Algorithm


  • Input:

    • Take a string as input.
  • Initialize:

    • Create a HashMap to store character frequencies.
    • java
      HashMap<Character, Integer> charFrequencyMap = new HashMap<>();
  • Traverse the String:

    • Iterate through each character in the input string.
  • Check Character Presence:

      • If yes, increment the corresponding frequency.
      • If no, add the character to the HashMap with a frequency of 1.

        Check if the character is already present in the HashMap.

    • java
      for (int i = 0; i < input.length(); i++) {
          char currentChar = input.charAt(i);
          if (charFrequencyMap.containsKey(currentChar)) {
              charFrequencyMap.put(currentChar, charFrequencyMap.get(currentChar) + 1);
          } else {
              charFrequencyMap.put(currentChar, 1);
          }
      }
  • Output:

    • Display the frequency of each character.

      java
  • for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) {
        System.out.println("Character: " + entry.getKey() + ", Frequency: " + entry.getValue());
    }

 

Code Examples

#1 Code Example- Find Frequency of Character

Code - Java Programming

public class Frequency {

    public static void main(String[] args) {
        String str = "This website is awesome.";
        char ch = 'e';
        int frequency = 0;

        for(int i = 0; i  <  str.length(); i++) {
            if(ch == str.charAt(i)) {
                ++frequency;
            }
        }

        System.out.println("Frequency of " + ch + " = " + frequency);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Frequency of e = 4
Advertisements

Demonstration


Java Programing Example to Find the Frequency of Character in a String-DevsEnv