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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
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.