笔试题目:编写一个函数用于去除字符串中多余的空格比如字符串
* “a b c c”(a,b间两个空格,b,c间三个空格),
* 处理后字符串为"a b c c"(a,b之间和b,c之间只有一个空格),
* 并分类输出个数(a:1, b:1, c:2);
首先去除多余的空格需要用到正则表达式:
String s = "a b b c d";
s=s.replaceAll("[ ]+", " ");
//s = s.replaceAll("\\s{2,}", " ");
//上面两种正则都可以实现
接下来就是分类输出每个字符的个数:
public static void main (String[] argc)
{
String s = "a b b c d";
s=s.replaceAll("[ ]+", " ");
//s = s.replaceAll("\\s{2,}", " ");
System.out.println(s);
String result = s.trim();
Map<String, Integer> map = new ConcurrentHashMap<>();
for (int i = 0; i < s.length(); i++) {
String substring = s.substring(i, i + 1);
if (map.containsKey(substring)){
map.put(substring,map.get(substring)+1);
}else{
map.put(substring,1);
}
}
//去除空格字符
if (map.containsKey(" ")){
map.remove(" ");
}
Set<Map.Entry<String, Integer>> entries = map.entrySet();
//输出统计个数
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}