- 用TreeMap集合装,字母装在key中,次数装在value中,把字符串转换成字符数组进行遍历
复制代码
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeMap;
- public class text01 {
- public static void main(String[] args) {
- TreeMap<Character,Integer> tr =ts("ddsgdfgdfgerfdgdfdf");
- Set<Character> set = tr.keySet();
- Iterator<Character> it = set.iterator();
- while(it.hasNext()){
- Character ch =it.next();
- Integer in = tr.get(ch);
- System.out.print(ch+"("+in+")");
- }
- }
- public static TreeMap<Character,Integer> ts(String s){
- TreeMap<Character,Integer> tr =new TreeMap<Character,Integer>();
- char[]ch =s.toCharArray();//字符串转换才字符数组
- for(int i=0;i<s.length();i++){ //遍历字符数组
- if(('z'>=ch[i] && ch[i]>='a') ||( 'Z'>=ch[i]&& ch[i]>='A'))
- {
- Integer value = tr.get(ch[i]);//用一个Ineger的变量获取
- int count = 0;//
- if(value!=null)//不等于null的话就把值赋给count
- {
- count=value;//把值付给count
- }
- count++;//自增一次
- tr.put(ch[i], count);//装入集合中
- }
- continue;
- }
- return tr;
- }
- }
复制代码
|