hashMap=newHashMap<>();for(inti=myStr.length()-1; i>=0;i--){ if(hashMap.conta"/> hashMap=newHashMap<>();for(inti=myStr.length()-1; i>=0;i--){ if(hashMap.conta">
Suppose the following is our string -
String myStr = "thisisit";
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); } }
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); HashMaphashMap = 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); } }
String =thisisit Counting occurrences of each character = {s=2, t=2, h=1, i=3}
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!