软件编程
位置:首页>> 软件编程>> java编程>> java中对字符串每个字符统计的方法

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

  发布时间:2023-09-23 13:53:16 

标签:字符串,统计


/*
    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;
    }
}


0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com