Java Program to Find the Frequency of Characters in a String - The Coding Shala

Home >> Java Programs >> Find the frequency of characters in a string

 In this post, we will learn how to write a Java program to find the frequency of characters in a string.

Java Program to Find the Frequency of Characters in a String

Write a Java Program to find the frequency of characters in a string. The given string contains a-z characters. 

Example 1:
Input: "hello"
output: e - 1
             h - 1
             l - 2
             o - 1

Approach 1

The given string contains only a-z characters that mean a maximum of 26 characters are there. We will create an integer array of size 26 and will store the count of each character in this array. 

The indexes of the count array will represent the characters. For example, index 0 will represent a, 1 as b, and so on. To find the indexes from characters will follow the below steps:

For example char = 'b', ASCII value of 'b' is 98. If we convert 'b' into int then we will get 98 and we know the ASCII value of a is 97, so

int index = (int) 'b' - 'a' = (int) 98-97 = 1

And if we do reverse then from integer to char will get our char back, like (char)1 + 'a' = 'b'.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void findFrequency(String str) {
        int[] counts = new int[26];
        for (int i=0; i <str.length(); i++) {
            char ch = str.charAt(i);

            // avoid space
            if (ch != ' ') {
                // get index, ascii value of char - ascii value of a
                // b - 'a' will return 1
                int index = ch - 'a';
                counts[index]++;
            }
        }

        System.out.println("Frequency of characters are below: ");
        for (int i=0; i<26; i++) {
            if (counts[i] != 0) {
                // get char
                // 1 + 'a' will return b
                char character = (char)(i + 'a');
                System.out.println(character + " - " + counts[i]);
            }
        }
    }

    public static void main(String[] args) {
        // string contains a-z only
        String str = "the coding shala";
        findFrequency(str);
    }
}

Output: 

Frequency of characters are below: 
a - 2
c - 1
d - 1
e - 1
g - 1
h - 2
i - 1
l - 1
n - 1
o - 1
s - 1
t - 1

Approach 2

We can use HashMap to store the character as key and their count as value. Using a map we can store all the other characters (A-Z) as well.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void findFrequency(String str) {
        Map<Character, Integer> map = new HashMap<>();

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

            // avoid space
            if (ch == ' ') continue;

            if (map.containsKey(ch)) {
                // if character is repeating then count+1
                map.put(ch, map.get(ch)+1);
            } else {
                map.put(ch, 1);
            }
        }

        // print counts
        System.out.println("Frequency of Characters are below: ");
        for (Map.Entry<Character, Integer> curr : map.entrySet()) {
            System.out.println(curr.getKey() + " - " + curr.getValue());
        }
    }

    public static void main(String[] args) {
        // string contains a-z only
        String str = "the coding shala";
        findFrequency(str);
    }
}

Output: 

Frequency of Characters are below: 
a - 2
c - 1
s - 1
t - 1
d - 1
e - 1
g - 1
h - 2
i - 1
l - 1
n - 1
o - 1


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala