import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class String_num {
public static void main(String[] args) {
String str="abcedfa";//随便定义字符串
shuZu(str);//用数组方法实现
System.out.println();
System.out.println("---------------------------------------");
hashMap(str);//用集合方式实现
}
public static void shuZu(String str){
char[]str_ch=str.toCharArray();//把字符串转换为字符数组
char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z'};//定义26个字母字符数组
int num[]=new int[26];//定义一个长度为26的整形数组用来为每个字母计数
for (int i = 0; i < str_ch.length; i++) {
for (int j = 0; j < ch.length; j++) {
if(ch[j]==str_ch[i]){//两层for循环进行比对
num[j]++;//计数
}
}
}
for (int i = 0; i < num.length; i++) {
if(num[i]!=0){//如果等于0就是在字符串中没有出现过
System.out.print(ch[i]+"["+num[i]+"], ");//打印
}
}
}
public static void hashMap(String str){
TreeMap<Character,Integer> map=new TreeMap<Character,Integer>();
for (int i = 0; i < str.length(); i++) {
if(!map.containsKey(str.charAt(i))){//这里也可以把str转换成字符数组
map.put(str.charAt(i),1);
}else{
int num=map.get(str.charAt(i));
num+=1;
map.put(str.charAt(i),num);
}
}
Set<Character> set=map.keySet();
Iterator<Character> iter=set.iterator();
while(iter.hasNext()){
char a=iter.next();
System.out.print(a+"["+map.get(a)+"], ");
}
}
}
//比较器用于二叉树
class MyComparator implements Comparator<Character>{
public int compare(Character c1, Character c2) {
int num=new Character(c1).compareTo(new Character(c2));
return num;
}
}
---------------------------------------
a[2], b[1], c[1], d[1], e[1], f[1],