/*
* 统计字符串”abadcdffbaeba”中每个字符出现了多少次,按次数排序并输出。
例如:c : 1,e : 1,d : 2,f : 2,b : 3,a : 4
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class StringTest{
Map tree = new TreeMap();
public static void main(String[] args){
String s= charCount("abadcdffbaeba");
System.out.println(s);
}
public static String charCount(String str){
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
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;
Integer value = tm.get(chs[x]);
if(value!=null)
count = value;
count++;
tm.put(chs[x],count);
count = 0;
/*
if(value==null){
tm.put(chs[x], 1);
}
else{
value = value + 1;
tm.put(chs[x], value);
}
*/
}
//System.out.println(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 ch = me.getKey();
Integer value = me.getValue();
sb.append(ch + ":" + value);
}
return sb.toString();
List<String> list = new ArrayList<String>();
Iterator it1 = tree.keySet().iterator();
String aa[][]=new String[tree.size()][tree.size()];
int jj=0;
while (it1.hasNext()) {
Object temp = it1.next();
aa[jj][0]=temp.toString();
aa[jj][1]=tree.get(temp).toString() ;
jj++;
}
for(int i=0;i<aa.length;i++){
for(int j=0;j<aa.length-i-1;j++){
if(Integer.parseInt(aa[j][1])>Integer.parseInt(aa[j+1][1])){
String temp=aa[j][1];
aa[j][1]=aa[j+1][1];
aa[j+1][1]=temp;
String temp1=aa[j][0];
aa[j][0]=aa[j+1][0];
aa[j+1][0]=temp1;
}
}
}
for (int i = 0, size = aa.length; i < size; i++){
System.out.print(aa[i][0]+":" + aa[i][1]);
}
}
}
|
|