java中对字符串每个字符统计的方法_java

分享到:


/*
    String name = "adsbsadgsadgtewterfsdf";
    eg a-->6,b-->1 d-->3 ...
    将字符串以a(字母)=>2(个数)存入Map集合框架中
   思路:1.将字符串转换成字符数组.
          2.定义一个Map集合,然后对字符数组进行遍历,如果Map集合中没有该元素就将该元素存入Map集合中,并定义一个计数器,将次数存入Map中,来达到目的 

*/
import java.util.*;
class CharMapDemo
{
    public static void main(String[] args)
    {
        String str = "abcedsadgsadfasdfaa";
        TreeMap<Character,Integer> tm = Pross(str);
        System.out.println(tm);
    }
    public static TreeMap<Character,Integer> Pross(String str)
    {
            char[] charArray = str.toCharArray();

            TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();

            for (int x = 0; x < charArray.length ;x++ )
            {
                if(!tm.containsKey(charArray[x]))
                {
                    tm.put(charArray[x],1);
                }
                else
                {
                    int count = tm.get(charArray[x])+1;
                    tm.put(charArray[x],count);
                }
            }
            return tm;
    }
}

昵    称:
验证码: