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

Java编程机试:获取某一字符串中(只要字母),每一个字母出现的次数输出格式为a(x)b(y)c(z).....m(n)

2015-10-14 11:14 761 查看
       好久没有写过博客了,一是因为最近趁国庆假期学习了一下集合Collection和map集合,二来下狠心早起去学车,时间也是很紧张,其实生活嘛,就是需要这种紧张的气氛。今天总结一下前几天写过的一个程序,好了,开始技术!

       在这里这个程序的要求如下:

       获取某一字符串如:"ag cCCCde3766ddgdfelakgjh"中,每一个字母(只要字母)出现的次数;要求输出格式是:a(2)b(1)h(4).....

       看到这个要求应该想到一下几点:

      (1)使用什么工具,因为操作的是字符串中的字母,所以先将字符串变成字符数组,字母和次数之间存在映射关系,是数组!---而且这种关系很多你就需要使用Map集合!可以保证唯一性的一方具备顺序----所以可以使用TreeMap。在这里使用Map集合是最为方便的,当然其他的方式也可以编出来。代码如下:

String str = "ag cCCCde3766ddgdfelakgjh";
char[] chs = str.toCharArray();
Map<Character,Integer> map = new TreeMap<Character,Integer>();<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">  </span>


      (2)如何进行遍历,按照编程的思路知道使用什么工具,就需要确定如何如何进行遍历了,按照TreeMap集合的操作特定,我们可以使用如下方法:

          遍历字符数组,用每一个字母作为键去查Map集合这个表;

              如果该字母键不存在,就将该字母为键,1为值,存储到map中;

              若果该字母键存在,就将该字母键对应取出并+1,在存储到map集合中。执行步骤可以是:

<span style="white-space:pre">		</span>if(value==null){
map.put(chs[i], 1);
}else{
map.put(chs[i], value+1);
}
具体代码如下:

for(int i=0;i<chs.length;i++){

if(!(chs[i]>='a'&&chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z')){
continue ;
}

//将数组中的字母作为键去查表
Integer value=map.get(chs[i]);
/*
//判断是否为空, //此处可以进行改进
if(value==null){
map.put(chs[i], 1);
}else{
map.put(chs[i], value+1);
}
*/
int count = 1;
if(value!=null){
count = value+1;
}
map.put(chs[i], count);
}
      (3)按照特定格式输出。

<span style="white-space:pre"> </span>StringBuilder sb = new StringBuilder();
Iterator<Character> it = map.keySet().iterator();
while(it.hasNext()){
Character key=it.next();
Integer value=map.get(key);

sb.append(key+"("+value+")");
}
       我们按以上三点进行思考,在编程的时候我们也按以上三点进行编程,所以总的代码如下:

public static void main(String[] args) {

String str = "ag cCCCde3766ddgdfelakgjh";

String s = getCharCount(str);

System.out.println(s);

}

public static String getCharCount(String str) {

//将字符串变成字符数组。
char[] chs = str.toCharArray();

//定义map集合表
Map<Character,Integer> map = 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=map.get(chs[i]);
/*
//判断是否为空, //此处可以进行改进
if(value==null){
map.put(chs[i], 1);
}else{
map.put(chs[i], value+1);
}
*/
int count = 1;
if(value!=null){
count = value+1;
}
map.put(chs[i], count);
}
return mapToString(map);
}

public static String mapToString(Map<Character, Integer> map) {

StringBuilder sb = new StringBuilder();
Iterator<Character> it = map.keySet().iterator();
while(it.hasNext()){
Character key=it.next();
Integer value=map.get(key);

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

}运行结果是:



有需要的朋友可以复制运行!

 

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