以下是代码全文:
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'))有这个判断就够了,下面转成小写字符我认为没啥作用,多此一举,或者写这段代码的人加上这个更加保险吧;
个人见解,仅供参考;如有作用,麻烦告知;
你给出的红框部分就是判断某个字符是不是26个小写字母,如果不是小写字母(即条件!成立),就continue不予处理。