JAVA-计算一个字符串中每个字符的出现的次数
程序员文章站
2024-03-17 11:55:58
...
import java.util.*;
public class StringCharNumberDemo {
public static void main(String[] args) {
//后台输入一个字符串
Scanner scanner = new Scanner(System.in);
String strings = scanner.next();
//将字符串转化为字符数组
char[] chars = strings.toCharArray();
//创建一个hashMap来存放,字符及其数量<K,V>
LinkedHashMap<Character,Integer> hashMap = new LinkedHashMap<>();
for (char aChar : chars) {
if (!hashMap.containsKey(aChar)) {
hashMap.put(aChar, 1);
} else {
hashMap.put(aChar, hashMap.get(aChar) + 1);
}
}
//遍历Map
Set<Map.Entry<Character, Integer>> entries = hashMap.entrySet();
for (Map.Entry<Character, Integer> next : entries) {
System.out.println(next);
}
}
}