Java Program to find character counts in a String :
In this tutorial, we will find the count of each characters in a given string (updated version).
Solution :
- First get the string input from the user
- Create one hashmap with key as ‘character’ and value as ‘integer’ . Count of each character will be stored as value with key as the character.
- Scan the string character by character
- Check for each character : if no key equalt to the character is available in the hashmap , add one new key as the character and value as 1.
- If key is available, increment the value by one.
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String line;
int value;
Scanner sc = new Scanner(System.in);
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
System.out.println("Enter a String :");
line = sc.nextLine();
for (int i=0; i<line.length(); i++){
if(map.containsKey(line.charAt(i))){
value = map.get(line.charAt(i));
value ++;
map.put(line.charAt(i),value);
}else{
map.put(line.charAt(i),1);
}
}
for ( Character key : map.keySet()){
System.out.println("Character : '"+key+"' Count :"+map.get(key));
}
}
}
Similar tutorials :
- Java program to find the number of vowels and digits in a String
- Java program to rotate each words in a string
- Java program to capitalize first letter of each word in a string
- Java program to convert a string to boolean
- Java program to replace string in a file
- Java program to find the duplicate elements in an array of Strings