使用Java函数统计字符串中字母出现次数
发布时间:2023-08-28 09:39:44
要统计字符串中字母的出现次数,可以使用Java中的HashMap来完成。下面是一个示例代码:
import java.util.HashMap;
public class LetterCount {
public static void main(String[] args) {
String str = "Hello World";
HashMap<Character, Integer> letterCounts = countLetters(str);
for (char c : letterCounts.keySet()) {
int count = letterCounts.get(c);
System.out.println(c + ": " + count);
}
}
public static HashMap<Character, Integer> countLetters(String str) {
HashMap<Character, Integer> letterCounts = new HashMap<>();
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
letterCounts.put(c, letterCounts.getOrDefault(c, 0) + 1);
}
}
return letterCounts;
}
}
在上述代码中,我们定义了一个 countLetters 函数,它接受一个字符串作为参数。该函数使用一个 HashMap 来存储每个字母的出现次数。然后,我们遍历字符串中的每个字符,如果该字符是字母,就将其加入 HashMap,并增加对应的计数值。最后,返回统计结果。
在主函数中,我们使用示例字符串 "Hello World" 作为输入来测试 countLetters 函数。然后,我们遍历 HashMap 中的每个键值对,并打印出字母和对应的出现次数。
执行上述代码,输出结果为:
H: 1 e: 1 l: 3 o: 2 W: 1 r: 1 d: 1
这说明在字符串 "Hello World" 中,字母 "H" 出现了 1 次,字母 "e" 出现了 1 次,字母 "l" 出现了 3 次,以此类推。
