以下是代碼全文:
package com.imooc;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class MapTest {
public static void main(String[] args) {
String str = "fdg+avAdc bs5dDa9c-dfs";
String s = getCharCount(str);
System.out.println(s);
}
public static String getCharCount(String str){
char[] chs = str.toCharArray();
Map<Character,Integer> map = new TreeMap<Character,Integer>();
for(int i = 0;i<chs.length;i++){
if(!(chs[i]>='a'&& chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z'))
if(!(Character.toLowerCase(chs[i])>='a' && Character.toLowerCase(chs[i])<'z'))
continue;
Integer value = map.get(chs[i]);
int count = 0;
if(value!=null){
count = value+1;
}
count++;
map.put(chs[i], count);
}
return mapToString(map);
}
private static String mapToString(Map<Character,Integer> map){
StringBuilder sb = new StringBuilder();
Iterator<Character> it = map.keySet().iterator();
while(it.hasNext()){
Character key = it.next();
Integer value = map.get(key);
sb.append(key+"("+value+")");
}
return sb.toString();
}
}
這段代碼的作用就是統計一串字符串中各個字母(A-Z、a-z)的個數,而ASSII碼中A-Z、a-z的值是**連續**的,所以if(!(chs[i]>='a'&& chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z'))有這個判斷就夠了,下面轉成小寫字符我認為沒啥作用,多此一舉,或者寫這段代碼的人加上這個更加保險吧;
個人見解,僅供參考;如有作用,麻煩告知;