- import java.util.*;
- class CharacterCount{
- public static void main(String[] args){
- String str = "a*b/cd. FEWg";
- str = getCharacterCount(str);
- System.out.println(str);
- }
- public static String getCharacterCount(String str){
- //创建一个map集合存放字母和对应的出现次数
- TreeMap<Character,Integer> charMap = new TreeMap<Character,Integer>();
- //需要遍历字符串中的所有字符,所以先将字符串转换为字符数组
- char[] charArr = str.toCharArray();
- //遍历charArr数组
- for(int i = 0;i < charArr.length; i++){
- //由于字符串中可能包含非字母的字符,所以对每个字符进行判断
- if(!(charArr[i] >= 'a' && charArr[i] <= 'z' || charArr[i] >= 'A' && charArr[i] <= 'Z')){
- continue;
- }
- Integer value = charMap.get(Character.valueOf(charArr[i]));
- //经过判断后,剩下的字符都是字母了
- //存入map之前首先判断该字母是否已经存在于map中,如果不存在则以该字母作为键,以1作为值存入map中
- //如果该字母已经存在于map中,则将对应的值加1后再存入map中
- if(value == null){
- //charMap.put(charArr[i],1);
- value = 1;
- }else{
- //charMap.put(charArr[i],++value);
- value++;
- }
- charMap.put(charArr[i],value);
- value = 0;
- }
- //遍历map,在遍历过程中,将遍历到的键值对存入StringBuilder中
- StringBuilder sb = new StringBuilder();
- Set<Character> keySet = charMap.keySet();
- for(Iterator<Character> it = keySet.iterator();it.hasNext();){
- //获取键
- Character key = it.next();
- //根据键获取值
- Integer value = charMap.get(key);
- //将键值对存入StringBuilder中
- sb.append(key + "("+ value +")");
- }
- return sb.toString();
- }
- }
复制代码
请指正...... |
|