/*
Enter a string: almost lover 123
a appers 1 time.
e appers 1 time.
l appers 2 times.
m appers 1 time.
o appers 2 times.
r appers 1 time.
s appers 1 time.
t appers 1 time.
v appers 1 time.
*/
import java.util.Scanner;
public class CountLetter {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
int[] counts = countLetters(str);
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((char)(i + 'a') + " appers " + counts[i] + ((counts[i] > 1) ? " times." : " time."));
}
}
}
public static int[] countLetters(String str) {
final int totalLetters = 26;
int[] counts = new int[totalLetters];
for (int i = 0, j; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
counts[str.charAt(i) - 'a']++;
}
return counts;
}
}
统计字符串中每个字母的个数
最新推荐文章于 2022-07-10 21:43:38 发布
本文介绍了一个简单的Java程序,该程序可以接收用户输入的一串文本,并统计出每个英文字母出现的次数。通过使用`Scanner`类读取用户输入的字符串,程序能够有效地遍历每个字符并统计大小写字母的出现频率。
2693

被折叠的 条评论
为什么被折叠?



