A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王艳静 中级黑马   /  2015-8-31 16:36  /  221 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

循环加判断时的两种写法。

举例:取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)..

不满足条件跳出当前循环。
  1.         public static Map<Character,Integer> getCharCount(String str) {
  2.                 Map<Character,Integer> map = new TreeMap<Character,Integer>();  //定义map集合
  3.                 char key;
  4.                 for (int i = 0; i < str.length(); i++) {   //遍历字符数组,获取每一个字母
  5.                         key = str.charAt(i);
  6.              if(!(key+"").matches("[a-z[A-Z]]")){   //过滤掉非字母字符
  7.                         continue;
  8.                     }
  9.                         Integer value = map.get(key);    //将遍历到的字母作为键去查表,获取值
  10.                         int count = 0;     //用于记录次数
  11.                         if(value != null){   //判断次数是否存在
  12.                                 count = value;     //存在,就用count记录次数
  13.                         }
  14.                         count++;           //次数不存在,就不记录,只对count自增变成1
  15.                         map.put(key, count);   //将字符和次数进行存储
  16.                 }
  17.                 return map;
  18.         }
复制代码


要执行的代码在if语句内部。
  1.         public static Map<Character,Integer> getCharCount(String str) {
  2.                 Map<Character,Integer> map = new TreeMap<Character,Integer>();  //定义map集合
  3.                 char key;
  4.                 for (int i = 0; i < str.length(); i++) {   //遍历字符数组,获取每一个字母
  5.                         key = str.charAt(i);
  6.              if((key+"").matches("[a-z[A-Z]]")){   //过滤掉非字母字符
  7.                              Integer value = map.get(key);    //将遍历到的字母作为键去查表,获取值
  8.                             int count = 0;     //用于记录次数
  9.                             if(value != null){   //判断次数是否存在
  10.                                     count = value;     //存在,就用count记录次数
  11.                             }
  12.                             count++;           //次数不存在,就不记录,只对count自增变成1
  13.                             map.put(key, count);   //将字符和次数进行存储
  14.                     }
  15.                 }
  16.                 return map;
  17.         }
复制代码


期待大神来解答。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马