import java.util.*;
/*
* 练习2: "asdadwrffcfg"获取该字符串中字母出现的个数 打印结果 a(2)d(1)
*
* 注意到字母和次数之间有映射关系,可以选择map集合
*
* 思路 1.将字符串转换成字符数组,因为要对每个字母进行操作
* 2.定义一个Map集合,因为打印要有顺序,所以用treemap集合
* 3.遍历字符数组
* 将每个字母作为key去查map集合
* 如果返回null,就将字母和1存入到集合中
* 如果返回数字,就把次数++,再存入到集合中,覆盖原有的值
* 4.将Map集合中的数据变成指定字符串形式返回
*
* */
class TreeMap练习2
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
sop(charCount("**..asdwwdwdwdwd"));
}
public static String charCount(String str)
{
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
for(int x=0; x<chs.length; x++)
{
if(!(chs[x]>='a'&&chs[x]<='z' || chs[x]>='A'&&chs[x]<='Z'))
continue;
Integer value = tm.get(chs[x]);
if(value == null)
{
tm.put(chs[x], 1);
}
else
{
tm.put(chs[x],++value);
}
}
//sop(tm);
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character,Integer>> entryset = tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it = entryset.iterator();
while(it.hasNext())
{
Map.Entry<Character,Integer> me = it.next();
Character key = me.getKey();
Integer value = me.getValue();
sb.append(key+"("+value+")");
}
return sb.toString();
}
}
java基础入门----TreeMap练习2
最新推荐文章于 2021-10-06 13:30:06 发布