黑马程序员技术交流社区
标题:
按照a(1)b(2)...格式打印字符串
[打印本页]
作者:
Adualtbird
时间:
2015-9-15 16:42
标题:
按照a(1)b(2)...格式打印字符串
/*
需求:"lajkflajrlwwjefakfjlsdghasdqw"获取该字符串出,每个字母出现的次数,
希望打印结果如a(1)b(3)...
思路:
1、字符和次数以键值对形式出现,且字母按照自然顺序排列,考虑用TreeMap集合存处
2、将字符串转化成字符数组,进行遍历,在遍历过程中,如果集合中已经存在某个字符,就将其值加1存入
如果不存在该字符,就将该字符和1存入
3、遍历集合,将集合内的键和值按照既定格式添加到StringBuilder中,然后转化成字符串返回
*/
import java.util.*;
class TreeMapTest2
{
public static void main(String[] args)
{
String str="lajkflajrlw*wjdfd-2+efakfjlsdghasdqw";
str=printChar(str);
System.out.println(str);
}
public static String printChar(String str){
TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();
char[] chs=str.toCharArray();
int count=0;
for(int x=0;x<chs.length;x++){
if(!(chs[x]>='a'&&chs[x]<='z'||chs[x]>='A'&&chs[x]<='z'))
continue;
if(!tm.containsKey(chs[x]))
count=1;
else{
count=tm.get(chs[x]);
count++;
}
tm.put(chs[x],count);
count=0;
}
StringBuilder sb=new StringBuilder();
Set<Map.Entry<Character,Integer>> entry=tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it=entry.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();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2