Here we will show you two solutions to count characters from the given string in java.
Solution #1 : Using Map
CharacterCountUsingMap.java
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 45 46 47 48 49 50 51 52 53 54 55 56 | package com.javacodepoint.programs; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class CharacterCountUsingMap { //Main method public static void main(String[] args) { // String variable to take a string input from the user String str = null ; // Map variable to store the count Map<Character,Integer> map = new HashMap<>(); // Creating scanner class object for reading user input Scanner sc = new Scanner(System.in); System.out.println( "Please enter a string to count the characters: " ); // reading the string input str = sc.next(); // making string in lowercase str = str.toLowerCase(); //iterate the string from beginning to end for ( int i= 0 ; i<str.length(); i++) { // pick the character char ch=str.charAt(i); if (map.containsKey(ch)) { //if character exist, increase count by 1 int count=map.get(ch); map.put(ch, count + 1 ); } else { //if character doesn't exist, initialize with 1 map.put(ch, 1 ); } } //Printing the final result by iterating the map Iterator<Character> it= map.keySet().iterator(); while (it.hasNext()) { char ch = it.next(); int count = map.get(ch); System.out.println(ch+ " => " +count); } } } |
OUTPUT:
Please enter a string to count the characters:
javacodepoint
p => 1
a => 2
c => 1
d => 1
t => 1
e => 1
v => 1
i => 1
j => 1
n => 1
o => 2
Solution #2 : Using Array
CharacterCountUsingArray.java
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 45 46 47 48 | package com.javacodepoint.programs; import java.util.Scanner; public class CharacterCountUsingArray { public static void main(String[] args) { // String variable to take a string input from the user String str = null ; // count array to hold the character count int count[] = new int [ 26 ]; // Creating scanner class object for reading user input Scanner sc = new Scanner(System.in); System.out.println( "Please enter a string to count the characters: " ); // reading the string input str = sc.next(); // making string in lowercase str = str.toLowerCase(); // iterate the string from beginning to end for ( int i = 0 ; i < str.length(); i++) { // pick the character and convert in ASCII no int ch = ( int ) str.charAt(i); // 97 is the ascii value for a count[ch - 97 ] = count[ch - 97 ] + 1 ; } // Printing the final result for ( int i = 0 ; i < count.length; i++) { int totalCount = count[i]; //checking the character was present in string or not if (totalCount > 0 ) { char ch = ( char ) ( 97 + i); System.out.println(ch + " => " + totalCount); } } } } |
OUTPUT:
Please enter a string to count the characters:
apple
a => 1
e => 1
l => 1
p => 2