您的位置:首页 > 编程语言 > Java开发

java基础-打印字符串中字母出现次数

2018-01-03 17:53 295 查看
/*
* 打印字符串中字母出现次数,打印形式:a(1)c(2)....
* 分析:每一个字符都有对相应的映射关系,因此选择map集合
* 思路:
* 1、将字符串转换为字符数组,因为要对每个字符操作
* 2、定义一个map集合,又因为打印出来的字母有顺序,故使用treemap集合
* 3、遍历字符数组:
* 将每一个字母作为键去查map集合
* 如果返回Null,就将字母和1存放到map集合
* 如果不是Null,说明集合中已存在该字母,则获取该次数并自增,然后将
* 自增后的次数存入到map集合,覆盖带哦用原来键所对应的值
* 4、将map集合中的数据变成指定的字符串形式返回。
*
* */
package com.itheima.treemap;
import java.util.*;

public class MapTest3
{
public static void main(String[] args)
{
String s=charCount("abcdbbcccefd");
System.out.println(s);

}

private static String charCount(String str)
{
char[]chs=str.toCharArray();
TreeMap<Character,Integer>tm=new TreeMap<Character,Integer>();

for (int i = 0; i <chs.length; i++)
{
if(!(chs[i]>='a'&&chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z'))
continue;
Integer value=tm.get(chs[i]);
//第一种直接写法
/*if(value==null)
tm.put(chs[i],1);
else
{
value=value+1;
tm.put(chs[i],value);
}*/
//第二种简单写法
int count=0;
if(value!=null)//如果不为空,将value取出记录下来自增后put
count=value;
count++;//如果为空,自增,count=1
tm.put(chs[i],count);
}
//System.out.println(tm);

//打印形式a(1)c(2)....
StringBuilder sb=new StringBuilder();

Set<Map.Entry<Character,Integer>>es=tm.entrySet();
Iterator<Map.Entry<Character,Integer>>it=es.iterator();
while(it.hasNext())
{
Map.Entry<Character,Integer>me=it.next();
Character key=me.getKey();
Integer value=me.getValue();

sb.append(key+"("+value+")");
}

return sb.toString();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java