第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何解決:字符串中字母出現(xiàn)的次數(shù)

如何解決:字符串中字母出現(xiàn)的次數(shù)

呼喚遠(yuǎn)方 2023-07-19 15:38:55
我正在嘗試計算字符串中字母的出現(xiàn)次數(shù)。我在技術(shù)上編寫的代碼可以實(shí)現(xiàn)我想要的功能,但不是按照我想要的方式實(shí)現(xiàn)。例如,如果我輸入“Hello World”,我希望我的代碼返回“a=0 b=0 c=0 d=0 e=1 etc....”,而我編寫的代碼返回“H= 1、e=1、l=2 等等……”另外我如何確保它不區(qū)分大小寫并且不計算空格。代碼:    import java.util.Scanner;    public class Sequence {    private static Scanner scan = null;    public static void main(String[] args) {        scan = new Scanner(System.in);        String str = null;        System.out.print("Type text: ");        str = scan.nextLine();        int[] count = new int[255];        int length = str.length();            for (int i = 0; i < length; i++)             {                count[str.charAt(i)]++;            }            char[] ch = new char[str.length()];            for (int i = 0; i < length; i++)             {                ch[i] = str.charAt(i);                int find = 0;                for (int j = 0; j <= i; j++)                 {                    if (str.charAt(i) == ch[j])                find++;                }                if (find == 1)                 {                    System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");                }            }         }    }
查看完整描述

2 回答

?
慕村225694

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]);


查看完整回答
反對 回復(fù) 2023-07-19
?
月關(guān)寶盒

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個贊

更改str = scan.nextLine();str = scan.nextLine().toLowerCase().replaceAll("\\s+","");

.toLowerCase()是一種使字符串中的每個字符都小寫的方法。

.replaceAll()是一種用另一個字符替換一個字符的方法。在這種情況下,它將空白替換為空。


查看完整回答
反對 回復(fù) 2023-07-19
  • 2 回答
  • 0 關(guān)注
  • 142 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號