统计"This is my country, chinese! I love her. This is our company, lifeng." 中每个字符出现的次数,
并将其按照出现次数排列输出。
(输出格式:
a: 5
c: 3
d: 2
b: 1
)
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class CharacterCount {
public static void main(String[] args) {
String input = "This is my country, chinese! I love her. This is our company, lifeng.";
Map<Character, Integer> charCount = countCharacters(input);
// 将字符出现次数的映射按照出现次数进行排序
TreeMap<Character, Integer> sortedCharCount = new TreeMap<>(charCount);
// 输出每个字符及其出现次数
for (Map.Entry<Character, Integer> entry : sortedCharCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
private static Map<Character, Integer> countCharacters(String input) {
Map<Character, Integer> charCount = new HashMap<>();
// 遍历字符串中的每个字符
for (char c : input.toCharArray()) {
// 忽略非字母字符和空格
if (Character.isLetter(c) && !Character.isWhitespace(c)) {
// 将字符转换为小写形式
char lowercaseChar = Character.toLowerCase(c);
// 更新字符出现次数
charCount.put(lowercaseChar, charCount.getOrDefault(lowercaseChar, 0) + 1);
}
}
return charCount;
}
}