package com.stephen;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* 面试题: 请用代码来计算字符串"I'm go to swimming"中每一个字母出现的次数,并打印出来
*
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
String str = "I'm go to swimming";
Test test = new Test();
// 得到一个字符数组
test.sortArr(test.getCharArr(str));
}
/**
* 将所有字符放入map集合中
*
* @param str
*/
Map<Character, Integer> getCharArr(String str) {
char[] arr = str.toCharArray();
Map<Character, Integer> map;
map = new TreeMap<>(); // 这里用的TreeMap,让它有序
for (int i = 0; i < arr.length; i++) {
if (arr[i] == ' ') {
continue;
}
int count = 1;
Integer integer = map.get(arr[i]);
if (integer != null) {
count = integer + count;
}
map.put(arr[i], count);
}
return map;
}
/**
* 遍历map
* 打印结果
*
* @param map
*/
void sortArr(Map<Character, Integer> map) {
Iterator<Character> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Character key = iterator.next();
Integer integer = map.get(key);
System.out.println(" " + key + " | " + integer);
}
}
}