import java.util.Date;
import java.util.Scanner;
import javax.swing.*;
public class blogTryProject{
//统计输入字符串中每个字母,高效简洁的代码(运用了各种字符串的处理功能函数和类方法等)
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = input.nextLine();
int[] counts = countLetters(s.toLowerCase());
for(int i = 0;i < counts.length;i++){
if(counts[i] != 0)
System.out.println((char)('a'+i)+" appears "+
counts[i] + ((counts[i] == 1) ? " time" : " times"));
}
}
public static int[] countLetters(String s){
int[] counts = new int[26];
for(int i = 0;i < s.length();i++){
if(Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
}
java小练习之统计字符串中字符出现的次数
最新推荐文章于 2023-06-03 09:12:17 发布