搜索
写经验 领红包

java面试计算字符串中字符出现的次数(计算字符串中字符出现的次数java)

导语:java 面试 计算字符串中字符出现的次数

代码
    String sourceStr = &34;;Map<String,Integer> map1 = new HashMap<String,Integer>();Map<String,Integer> map2 = new HashMap<String,Integer>();Map<String,Integer> map3 = new HashMap<String,Integer>();//方法一String[] strsArry = sourceStr.split(&34;);for(int a=0;a<sourceStr.length();a++){String str = strsArry[a];if(map1.containsKey(str)){map1.put(str,map1.get(str)+1);}else{map1.put(str,1);}}//方法二char [] charArray = sourceStr.toCharArray();    for(int a=0;a<charArray.length;a++){String str = String.valueOf(charArray[a]);        if(map2.containsKey(str)){map2.put(str,map2.get(str)+1);}else{map2.put(str,1);}}//方法三for(int a=0;a<sourceStr.length();a++){String str = sourceStr.substring(a,a+1);if(map3.containsKey(str)){map3.put(str,map3.get(str)+1);}else{map3.put(str,1);}}System.out.println(&34;);Iterator<Map.Entry<String,Integer>> iterator = map1.entrySet().iterator();        while (iterator.hasNext()){Map.Entry<String,Integer> entry = iterator.next();String key = entry.getKey();System.out.println(&34;+key+&34;+entry.getValue());}System.out.println(&34;);Iterator<Map.Entry<String,Integer>> iterator2 = map2.entrySet().iterator();while (iterator2.hasNext()){Map.Entry<String,Integer> entry = iterator2.next();String key = entry.getKey();System.out.println(&34;+key+&34;+entry.getValue());}System.out.println(&34;);for(String key:map3.keySet()){System.out.println(&34;+key+&34;+map3.get(key));}
执行结果
方法一结果======================字符:a 2字符:b 2字符:c 2字符:s 9字符:d 11字符:e 2字符:f 11字符:g 2字符:h 3方法二结果======================字符:a 2字符:b 2字符:c 2字符:s 9字符:d 11字符:e 2字符:f 11字符:g 2字符:h 3方法三结果======================字符:a 2字符:b 2字符:c 2字符:s 9字符:d 11字符:e 2字符:f 11字符:g 2字符:h 3

本文内容由快快网络小葵整理编辑!