循环加判断时的两种写法。
举例:取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)..
不满足条件跳出当前循环。
- public static Map<Character,Integer> getCharCount(String str) {
- Map<Character,Integer> map = new TreeMap<Character,Integer>(); //定义map集合
- char key;
- for (int i = 0; i < str.length(); i++) { //遍历字符数组,获取每一个字母
- key = str.charAt(i);
- if(!(key+"").matches("[a-z[A-Z]]")){ //过滤掉非字母字符
- continue;
- }
- Integer value = map.get(key); //将遍历到的字母作为键去查表,获取值
- int count = 0; //用于记录次数
- if(value != null){ //判断次数是否存在
- count = value; //存在,就用count记录次数
- }
- count++; //次数不存在,就不记录,只对count自增变成1
- map.put(key, count); //将字符和次数进行存储
- }
- return map;
- }
复制代码
要执行的代码在if语句内部。
- public static Map<Character,Integer> getCharCount(String str) {
- Map<Character,Integer> map = new TreeMap<Character,Integer>(); //定义map集合
- char key;
- for (int i = 0; i < str.length(); i++) { //遍历字符数组,获取每一个字母
- key = str.charAt(i);
- if((key+"").matches("[a-z[A-Z]]")){ //过滤掉非字母字符
- Integer value = map.get(key); //将遍历到的字母作为键去查表,获取值
- int count = 0; //用于记录次数
- if(value != null){ //判断次数是否存在
- count = value; //存在,就用count记录次数
- }
- count++; //次数不存在,就不记录,只对count自增变成1
- map.put(key, count); //将字符和次数进行存储
- }
- }
- return map;
- }
复制代码
期待大神来解答。 |
|