TreeMap统计字符串中字符的个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cnd2449294059/article/details/81660644
package com.cnd05;

import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

/**
 * TreeMap统计字符串中字符个数
 * @author ndci
 *
 */
public class TreeMapDemo {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		System.out.println("请输入一个字符串:");
		String line=sc.nextLine();
		//定义TreeMap集合对象
		TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();
		//字符串转字符数组
		char [] chs=line.toCharArray();
		//遍历字符数组->从TreeMap集合中找是否存在相应的键,如果存在,键值value+1,否则,键值设置为1.
		for(char c:chs) {
			Integer i = tm.get(c);
			if(i==null) {
				tm.put(c, 1);
			}else {
				i++;
				tm.put(c, i);
			}
		}
		//定义一个字符串缓存对象
		StringBuilder sb=new StringBuilder();
		
		//遍历TreeMap集合--增强for循环
		Set<Character> set=tm.keySet();
		for(Character key:set) {
			Integer value=tm.get(key);
			sb.append(key).append("(").append(value).append(")");
		}
		//字符串缓存对象转换为字符串
		String result=sb.toString();
		System.out.println("result:"+sb);
	}

}

猜你喜欢

转载自blog.csdn.net/cnd2449294059/article/details/81660644