美文网首页
机试题:检索一个字符串中每个字符出现的个数

机试题:检索一个字符串中每个字符出现的个数

作者: 大小说家RCQ | 来源:发表于2017-06-04 19:17 被阅读0次

遇到的机试题

import java.util.*;


public class Demo{
    public static void main(String args[])throws Exception{
      String str = "skjaghakioutreitou"; //要检索的字符串
      char[] arr = str.toCharArray(); //将字符串转换成字符数组
      Map<Character,Integer> map = Demo.charNoum(arr); // 直接在主方法中调用检索的方法,返回一个map集合
      Iterator it = map.entrySet().iterator();  //使用iterator遍历map集合
      while(it.hasNext()){
          Map.Entry p = (Map.Entry)it.next();
          System.out.println(p.getKey()+"出现的次数是:"+p.getValue());

      }
    }
    public static Map<Character,Integer> charNoum(char[] args){  //传入的参数是字符数组,返回map集合
        Map<Character,Integer> map = new TreeMap<>();  //实例化一个treeMap 
         for(int i=0;i<args.length;i++){   
             char temp = args[i];      //遍历得到每个字符
             if(!map.containsKey(temp)){  //判断字符是否在key中存在,不存在初始化为1
                 map.put(temp,1);    // 字符自动装箱为Character对象
             }else{
                 int auto = map.get(temp)+1;  // 如果存在,通过key取出value 将数值加1
                 map.put(temp,auto);
             }
         }
         return map;
    }
}

相关文章

网友评论

      本文标题:机试题:检索一个字符串中每个字符出现的个数

      本文链接:https://www.haomeiwen.com/subject/sycbfxtx.html