Rust語言編程實例100題-017

Rust語言編程實例100題-017

題目:在控制臺隨便輸入一行字符,分別統(tǒng)計出其中英文字母、空格、數(shù)字和其它字符的個數(shù)。

程序分析:可以通過> < 比較判斷當前的字符屬于什么類型的字符。注入從控制臺輸入后的最后字符是'\n'。

輸出格式:字母的個數(shù)是 x1, 空格的個數(shù)是 x2, 數(shù)字的個數(shù)是x3, 其它字符的個數(shù)是 x4。

知識點:循環(huán),輸入

fn main() {
    let mut input_data = String::new();
    println!("請輸入一些字符:");
    std::io::stdin().read_line(&mut input_data).expect("read line error !");

    // 字母
    let mut letters = 0;
    // 空格
    let mut spaces = 0;
    // 數(shù)字
    let mut digits = 0;
    // 其它
    let mut others = 0;

    // trim去除最后的 \n 字符
    for x in input_data.trim().chars() {
        if (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') {
            letters += 1;
        } else if x >= '0' && x <= '9' {
            digits += 1;
        } else if x == ' ' {
            spaces += 1;
        } else {
            others += 1;
        }
    }

    println!("字母的個數(shù)是 {}, 空格的個數(shù)是 {}, 數(shù)字的個數(shù)是{}, 其它字符的個數(shù)是 {}", letters, spaces, digits, others);
}

程序執(zhí)行結(jié)果:

請輸入一些字符:
study rust diary 001 -- hello world!
字母的個數(shù)是 24, 空格的個數(shù)是 6, 數(shù)字的個數(shù)是3, 其它字符的個數(shù)是 3

Process finished with exit code 0
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容