统计字符串中重复元素出现的次数

首先输入一个字符串,然后使用toCharArray()方法将其转换成字符数组,后遍历数组,创建HashMap集合存放字符和过元素出现的次数、、、

public class TestDemo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入字符串:");
		String str = sc.nextLine();
                
		HashMap<Character, Integer> hashMap = new HashMap<>();
                //将字符串转换成字符数组
		char[] chs = str.toCharArray();
                //遍历字符数组
		for (char c : chs) {
			if (hashMap.containsKey(c)) {
                              //如果包含先获取字符对应的次数,然后次数自增1后,再次存入原字符索引
				Integer num = hashMap.get(c);
				num++;
				hashMap.put(c, num);
			}else {
                                //如果不包含则直接存入,并且将次数初始化为1
				hashMap.put(c, 1);
			}
		}
		System.out.println(hashMap);
	}
}

猜你喜欢

转载自blog.csdn.net/moxiaomo0804/article/details/89490808