黑马程序员技术交流社区
标题:
如何实现以下效果
[打印本页]
作者:
占琳
时间:
2012-10-20 20:27
标题:
如何实现以下效果
本帖最后由 w129160 于 2012-10-21 11:24 编辑
比如输入一连串字符串 然后打印出每个字母出现的次数 比如dffag
打印出d:1 f:2 a:1 g:1
作者:
官仁杰
时间:
2012-10-20 20:48
import java.util.*;
public class MapTest2 {
public static void main(String[] arg){
String str = "aaaasdsdszA";
System.out.println(charCount(str));
}
public static String charCount(String str){
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
int count = 0;
for(int i = 0;i<chs.length;i++){
if( chs[i]>='a'&&chs[i]<='z'|| chs[i]>='A'&&chs[i]<='Z')
if(tm.containsKey(chs[i])){
count = tm.get(chs[i]);
tm.put(chs[i], count+1);
}
else tm.put(chs[i],1);
}
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<Character,Integer> me = it.next();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch+":"+value+" ");
}
return sb.toString();
}
}
复制代码
作者:
刘伟平
时间:
2012-10-20 20:49
将字符串str.toCharArray()转换为字符数组,创建一个Map集合,遍历字符数组。
如果当前字符在Map集合中不存在,就将这个字符作为Map集合的键添加到集合中,并设置值为1;
如果当前字符在Map集合中存在,就将其值加1。
遍历并输出Map集合中的键值。
作者:
李琼
时间:
2012-10-20 20:56
package com.itheima;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/*
* 取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)...
*/
public class Test3 {
public static void main(String[] args) {
//定义变量
String str = "abcdekka27qoq";
//定义hashMap
HashMap<Character, Integer> lqhm = new HashMap<Character, Integer>();
//遍历string字符串
for (int i = 0; i < str.length(); i++) {
//取出来单个的字母
char c = str.charAt(i);
//查看HashMap里面有没有现在所要找的值,如果没有的话,就给它附初始值为1,如果有,就+1
Integer integer = lqhm.get(c);
if (integer == null)
integer = 1;
else
integer++;
lqhm.put(c, integer);
}
//变量数组,另外加上括号~
Set<Map.Entry<Character, Integer>> entrys = lqhm.entrySet();
for (Map.Entry<Character, Integer> entry : entrys) {
System.out.print(entry.getKey() + "(" + entry.getValue() + ")");
}
}
}
复制代码
昨天刚做的入学测试题,你参考一下。
作者:
灵感
时间:
2012-10-20 21:26
本帖最后由 严学韦 于 2012-10-20 21:32 编辑
<P>package LianXi;
/*
* 需求:打印一个字符串中每个字符出现的次数
* */
import java.util.*;//导入JAVA工具包
public class AppearTimeDemo {
public static void main(String args[]){
String s = "HeiMa ChengXuYuan"; //测试字符串
Map<Character, Integer> result = getCharMaps(s);
System.out.println(result);//打印出字符串中各字符出现的次数!
}
public static Map<Character, Integer> getCharMaps(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();//定义一个Map集合
for(int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
Integer count = map.get(c);
map.put(c, count == null ? 1 : count + 1);
}
return map;
}
}</P>
复制代码
这个问题我记得毕老师专门讲过的,可以再细看视频的
结果.jpg
(5.06 KB, 下载次数: 5)
下载附件
2012-10-20 21:32 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2