我正在尝试获取系统输入并检查用户是否输入了是或否.我的字符串转换是错误还是什么?if块不执行.
use std::io;
fn main() {
let mut correct_name = String::new();
io::stdin().read_line(&mut correct_name).expect("Failed to read line");
if correct_name == "y" {
println!("matched y!");
} else if correct_name == "n" {
println!("matched n!");
}
}
Run Code Online (Sandbox Code Playgroud)
She*_*ter 12
而不是trim_right_matches,我建议使用trim_right甚至更好,只是trim:
use std::io;
fn main() {
let mut correct_name = String::new();
io::stdin().read_line(&mut correct_name).expect("Failed to read line");
let correct_name = correct_name.trim();
if correct_name == "y" {
println!("matched y!");
} else if correct_name.trim() == "n" {
println!("matched n!");
}
}
Run Code Online (Sandbox Code Playgroud)
最后一种情况处理许多类型的空白:
返回删除了前导和尾随空格的字符串切片.
'Whitespace'是根据Unicode派生核心属性White_Space的术语定义的.
所以Windows/Linux/macOS无关紧要.
你也可以使用修剪结果的长度来截断原文String,但在这种情况下你应该只使用trim_right!
let trimmed_len = correct_name.trim_right().len();
correct_name.truncate(trimmed_len);
Run Code Online (Sandbox Code Playgroud)
read_line包括返回字符串中的终止换行符.添加.trim_right_matches("\r\n")到您的定义中correct_name以删除终止换行符.
| 归档时间: |
|
| 查看次数: |
1646 次 |
| 最近记录: |