Java程序检查String中每个字符的出现

为了发现字符串中每个字符的出现,我们可以使用Java的Map实用程序。在Map中,键不能重复,因此将字符串中的每个字符都作为Map的键,如果该字符将与每个键对应的初始值设置为1不会在以前插入map中。现在在插入过程中重复出现一个字符时,因为Map中的key将其值增加一。对每个字符继续执行此操作,直到将所有字符串都插入。

示例

public class occurenceOfCharacter {
   public static void main(String[] args) {
      String str = "SSDRRRTTYYTYTR";
      HashMap <Character, Integer> hMap = new HashMap<>();
      for (int i = str.length() - 1; i > = 0; i--) {
         if (hMap.containsKey(str.charAt(i))) {
            int count = hMap.get(str.charAt(i));
            hMap.put(str.charAt(i), ++count);
         } else {
            hMap.put(str.charAt(i),1);
         }
      }
      System.out.println(hMap);
   }
}

输出结果

{D=1, T=4, S=2, R=4, Y=3}