Java程序统计每个字符的出现
假设以下是我们的字符串-
String myStr = "thisisit";
为了计算发生次数,我们使用了HashMap。循环使用并使用containsKey(0和charAt()
method,计算上述字符串中每个字符的出现次数-
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); } }
示例
以下是计算每个字符的出现次数的程序-
import java.util.HashMap; public class Demo { public static void main(String[] args) { String myStr = "thisisit"; System.out.println("String ="+myStr); 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); } } System.out.println("Counting occurrences of each character = "+hashMap); } }
输出结果
String =thisisit Counting occurrences of each character = {s=2, t=2, h=1, i=3}