2 回答

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個贊
你只需要一個 26 (s) 的數(shù)組int
,因?yàn)樽帜副碇兄挥?26 個字母。在分享代碼之前,請務(wù)必注意 Javachar
是整型(例如,'a' + 1 == 'b')。該屬性很重要,因?yàn)樗试S您確定數(shù)組中的正確偏移量(特別是如果您強(qiáng)制輸入為小寫)。就像是,
Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
? ? char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
? ? if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
? ? ? ? count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
? ? }
}
for (int i = 0; i < count.length; i++) {
? ? if (count[i] != 0) {
? ? ? ? System.out.printf("%c=%d ", 'a' + i, count[i]);
? ? }
}
System.out.println();
如果您確實(shí)想查看所有計數(shù)為零的字母(對我來說似乎毫無意義),請更改
if (count[i] != 0) {
? ? System.out.printf("%c=%d ", 'a' + i, count[i]);
}
刪除if并且只是
System.out.printf("%c=%d ", 'a' + i, count[i]);

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個贊
更改str = scan.nextLine();
為str = scan.nextLine().toLowerCase().replaceAll("\\s+","");
.toLowerCase()
是一種使字符串中的每個字符都小寫的方法。
.replaceAll()
是一種用另一個字符替換一個字符的方法。在這種情況下,它將空白替換為空。
添加回答
舉報