Count Number of Times Each Character Appears in a String Java Program

Daftar Isi: (toc)

In this post we'll see a Java program to count the total number of times each character occurs in the given String. Here two ways are given for counting the occurrences of each character in the given String; one using HashMap and another one by using char array.

Counting the frequency of characters in String using HashMap

Here it is done using HashMap provided by Java collection framework. Logic is to read one character at a time from the string and put it in HashMap; character as key, count as value (Initial value will be 1).

With every character that is read from the String check in the HashMap, if it already exists as a key or not. If it exists then increment the count otherwise add the key in HashMap with value 1.

public class CountCharacters {    
// method used to count characters in a String
public void countChars(String message){
Map<Character, Integer> numCharMap = new HashMap<Character, Integer>();
for(int i = 0; i < message.length(); i++){
// Take one character
char c = message.charAt(i);
// We don't need to count spaces
if(c == ' ')
continue;
// If that character is already there in the map
// then increase the value by 1
if(numCharMap.containsKey(c)){
numCharMap.put(c, numCharMap.get(c) + 1);
}else{
// otherwise put that character in the map
// with the value as 1
numCharMap.put(c, 1);
}
}
// Displaying the map values
Set<Map.Entry<Character, Integer>> numSet = numCharMap.entrySet();
for(Map.Entry<Character, Integer> m : numSet){
System.out.println("Char- " + m.getKey() + " Count " + m.getValue());
}
}

public static void main(String[] args) {
CountCharacters cc = new CountCharacters();
cc.countChars("I am an Indian");
}
}

Output

Char- a Count 3
Char- d Count 1
Char- I Count 2
Char- i Count 1
Char- m Count 1
Char- n Count 3

Values are displayed by looping the HashMap, entrySet is used to iterate the map, which gives the key value pair as Entry object.

Counting the frequency of characters in String using char array

In the Java program to count total number of occurrences of each character in a String using char array, given String is converted to char array then you need to iterate the array starting from first index and check if that character is found again in the char array. If yes then increase the count. One thing you need to do is to remove all the occurrences of that character from the string after counting is done for that specific character.

public class CountCharacters {
public static void main(String[] args) {
CountCharacters cc = new CountCharacters();
cc.countChars("I am an Indian");
}

public void countChars(String str){
char[] strArr;
while(str.length() != 0){
strArr = str.toCharArray();
char ch = strArr[0];
int count = 1;
for(int i = 1; i < strArr.length; i++){
if(ch == strArr[i]){
count++;
}
}
// We don't need to count spaces
if(((ch != ' ') && (ch != '\t'))){
System.out.println(ch + " - " + count);
}
// replace all occurrence of the character
// which is already iterated and counted
str = str.replace(""+ch, "");
}
}
}
Output
I - 2
a - 3
m - 1
n - 3
d - 1
i - 1

That's all for this topic Count Number of Times Each Character Appears in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Number of Words in a String Java Program
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Add Double Quotes to a String Java Program
  4. How to Reverse a String in Java
  5. Convert String to Byte Array Java Program

You may also like-

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. Marker Interface in Java
  5. How LinkedList Class Works Internally in Java
  6. Functional Interfaces in Java
  7. ConcurrentSkipListMap in Java With Examples
  8. Dependency Injection in Spring Framework
Find Out
Related Post



Ikuti AltairGate.com pada Aplikasi GOOGLE NEWS : FOLLOW (Dapatkan Berita Terupdate tentang Dunia Pendidikan dan Hiburan). Klik tanda  (bintang) pada aplikasi GOOGLE NEWS.

Jika ada Link Unduhan yang Error, Beri tahu Lewat Komen ya!

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad