/*
* 统计一个字符串中的所有字符个数,要有一个标记如果标记为true,
* 则统计所有字符如果,为false则只统计字母的个数
*
* 要求
* "abcdekka27qoqsft"
* 显示效果为:
*
* */
public class StatisCharNum {
private HashMap<Character, Integer> map=new HashMap<Character, Integer>();
private void statisCharNum(String str,boolean isAll){
for (int i = 0; i < str.length(); i++) {
char tmp=str.charAt(i);
if(map.containsKey(tmp)){
map.put(tmp, map.get(tmp)+1);
}else if(Character.isAlphabetic(tmp)||isAll){
map.put(tmp, 1);
}
}
}
public void show(String str,boolean isAll){
statisCharNum(str,isAll);
Set<Character> set = map.keySet();
StringBuilder sbu=new StringBuilder();
for (Character ch : set) {
if(ch.equals('\n')){
sbu.append("<换行>"+"("+map.get(ch)+")");
}else if(ch.equals(' ')){
sbu.append("<空格>"+"("+map.get(ch)+")");
}else if(ch.equals('\t')){
sbu.append("<制表>"+"("+map.get(ch)+")");
}else if(Character.isAlphabetic(ch)){
sbu.append(ch+"("+map.get(ch)+")");
}else {
sbu.append("<"+ch+">"+"("+map.get(ch)+")");
}
}
System.out.println(sbu.toString());
}
public static void main(String[] args) {
new StatisCharNum().show("abcdekka27qoqsfasehsefs",true);
}
}
|
|