美文网首页Rust语言编程实例100题
Rust语言编程实例100题-017

Rust语言编程实例100题-017

作者: L我是小学生 | 来源:发表于2021-07-02 12:37 被阅读0次

Rust语言编程实例100题-017

题目:在控制台随便输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析:可以通过> < 比较判断当前的字符属于什么类型的字符。注入从控制台输入后的最后字符是'\n'。

输出格式:字母的个数是 x1, 空格的个数是 x2, 数字的个数是x3, 其它字符的个数是 x4。

知识点:循环,输入

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;
    // 数字
    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!("字母的个数是 {}, 空格的个数是 {}, 数字的个数是{}, 其它字符的个数是 {}", letters, spaces, digits, others);
}

程序执行结果:

请输入一些字符:
study rust diary 001 -- hello world!
字母的个数是 24, 空格的个数是 6, 数字的个数是3, 其它字符的个数是 3

Process finished with exit code 0

相关文章

网友评论

    本文标题:Rust语言编程实例100题-017

    本文链接:https://www.haomeiwen.com/subject/vaveultx.html