Java program to count the number of occurrences of a character in a string!

 

Hello friends and dear programmers, today we are going to write a Java program which will count the number of occurrence of a character in a string.

Let’s see the code:

import java.util.LinkedHashMap;
import java.util.Scanner;

public class occur {

    public static void main(String[] args) {
        String str;
        char ch;

        Scanner in = new Scanner(System.in);

        //get the input
        System.out.println("Enter the string:");
        str = in.nextLine();
        //remove the space between the strings
        str = str.replaceAll(" ", "").trim();

        //LinkedHashMap allows insertion-order iteration over the map
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

        for (int i = 0; i < str.length(); i++) {
            //get the characters from the string for every loop
            ch = str.charAt(i);            
            //check if the string is already in the map
            if (map.containsKey(ch)) {
                //if yes, get the value from the array
                int val = map.get(ch);
                //and add the value + 1
                map.put(ch, val + 1);
            } else {
                //if no, map the character key,value=1
                map.put(ch, 1);
            }
        }
        //loop through the map to print each key and value pair 
        map.entrySet().stream().map((entry) -> {
            System.out.print(entry.getKey() + " occurs ");
            return entry;
        }).forEach((entry) -> {
            System.out.println(entry.getValue() + " time(s)");
        });

    }
}

Read the comments in the script to understand each and every class and functions used in the above program.

Leave a Comment

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

Scroll to Top