统计字符串中每个字母出现的次数,如a(1)b(3)c(2)...

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class MapTest {

	public static void main(String[] args) {
		String str = "aabcdekdiadkiekc";
		//方法一:通过集合的方式获取字符串中每个字母出现的次数
		getMapToString(str);
		//方法二:通过循环的方式获取字符串中每个字母出现的次数
		countString(str);
	}

	// 采用集合的方式统计字符串中每个字母出现的次数
	private static void getMapToString(String str) {
		// 将字符串转化为字符数组
		char[] c = str.toCharArray();
		TreeMap<Character, Integer> map = new TreeMap<>();
		// 遍历数组,将字母与字母出现的次数存TreeMap集合中
		for (int i = 0; i < str.length(); i++) {
			// 过滤字母以外的字符
			if (!(c[i] >= 'a' && c[i] <= 'z' || c[i] >= 'A' && c[i] <= 'Z')) {
				continue;
			}
			// 将数组中的字母作为键去查Map表
			Integer value = map.get(c[i]);
			if (value == null) {
				map.put(c[i], 1);
			} else {
				map.put(c[i], value + 1);
			}
		}
		//将map的key存入set集合中
		Set<Character> set = map.keySet();
		StringBuilder sb = new StringBuilder();
		//foreach遍历
//		for (Character s : set) {
//			Integer value = map.get(s);
//			sb.append(s + "(" + value + ")");
//		}
		// 获取迭代器并遍历集合
		Iterator<Character> it = set.iterator();
		while(it.hasNext()){
			Character key = it.next();
			Integer value = map.get(key);
			sb.append(key+"("+value+")");
		}
		System.out.println(sb.toString());
	}

	// for循环的方式统计字符串中每个字母出现的次数
	private static void countString(String str) {
		for (int i = 65; i < 123; i++) {// A~z的ASCII码值
			int count = 0;
			for (int j = 0; j < str.length(); j++) {
				if(i==str.charAt(j)){
					count++;
				}
			}
			if(count!=0){// 当count的个数为0时说明没有出现过该字母
				System.out.print((char)i+"("+count+")");
			}
		}
	}
}

运行结果

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值