/*
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;
}
}
统计字符串中每个字母的个数
最新推荐文章于 2024-04-16 17:11:59 发布