Pages

Counting Number of Character in a string
Write a program that will accept a string and count the occurance of each character and display them
Input
abhiaadibbbchibd
Output
Characters along with number of occurance
Number of a : 3
Number of b : 5
Number of c : 1
Number of d : 2
Number of h : 2
Number of i : 3
The simple approach to solve this problem is creating an integer array of Character.MAX_VALUE size. Then converting each character to integer that will represent the index value of that character.So, now we have to increment the previous value whenever same character is encountered. For example character a, b and c will be placed at index 97, 98 and 99 respectively. So, whenever these character encountered increment their previous value by 1.
import java.util.*;
class CharacterCount{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); int[] counts = new int[(int) Character.MAX_VALUE]; // If you are certain you will only have ASCII characters, I would use `new int[256]` instead
for (int i = 0; i < str.length(); i++) { char charAt = str.charAt(i); counts[(int) charAt]++; }
for (int i = 0; i < counts.length; i++) { if (counts[i] > 0) System.out.println("Number of " + (char) i + ": " + counts[i]); } } }
Another approach is to use java.util.Map instead of array. So, here we will check for a particular character inside map. If it contains then update the previous value of that character by 1 else put that character inside map with initial value 1.
import java.util.*;
class CharacterCount{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); String s = sc.next(); Map<Character, Integer> map = new HashMap<Character, Integer>();
for(int i=0; i<s.length(); i++){ char ch = s.charAt(i); if(map.get(ch) != null){ map.put(ch, map.get(ch)+1); } else { map.put(ch, 1); } } System.out.println(map); } }

No comments:

Post a Comment