Home > Java > javaTutorial > Java program to count occurrences of each character

Java program to count occurrences of each character

WBOY
Release: 2023-08-26 23:05:09
forward
1279 people have browsed it

Java program to count occurrences of each character

Suppose the following is our string -

String myStr = "thisisit";
Copy after login

To count the number of occurrences, we use a HashMap. Loop and use containsKey(0 and charAt() methods to count the number of occurrences of each character in the above string -

HashMap <Character, Integer> hashMap = new HashMap<>();
for (int i = myStr.length() - 1; i >= 0; i--) {
   if (hashMap.containsKey(myStr.charAt(i))) {
      int count = hashMap.get(myStr.charAt(i));
      hashMap.put(myStr.charAt(i), ++count);
   } else {
         hashMap.put(myStr.charAt(i),1);
   }
}
Copy after login

Example

The following is the program to count the number of occurrences of each character-

import java.util.HashMap;
public class Demo {
   public static void main(String[] args) {
      String myStr = "thisisit";
      System.out.println("String ="+myStr);
      HashMap  hashMap = new HashMap<>();
      for (int i = myStr.length() - 1; i >= 0; i--) {
         if (hashMap.containsKey(myStr.charAt(i))) {
            int count = hashMap.get(myStr.charAt(i));
            hashMap.put(myStr.charAt(i), ++count);
         } else {
            hashMap.put(myStr.charAt(i),1);
         }
      }
      System.out.println("Counting occurrences of each character = "+hashMap);
   }
}
Copy after login

Output

String =thisisit
Counting occurrences of each character = {s=2, t=2, h=1, i=3}
Copy after login

The above is the detailed content of Java program to count occurrences of each character. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template