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