我正在尝试获取用户输入并检查用户输入的是“y”还是“n”。令人惊讶的是,在下面的代码中,if
和 if else
都没有执行!显然,correct_name
既不是“y”也不是“n”。怎么可能?我是在做我的字符串转换错误还是什么?
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!");
}
}
最佳答案
read_line
在返回的字符串中包含终止换行符。
要删除它,请使用 trim_end
甚至更好,只是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 == "n" {
println!("matched n!");
}
}
最后一个案例处理多种类型的空白:
Returns a string slice with leading and trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space.
Windows/Linux/macOS 应该无关紧要。
您也可以使用修剪结果的长度来截断原始 String
,但在这种情况下您应该只使用 trim_end
!
let trimmed_len = correct_name.trim_end().len();
correct_name.truncate(trimmed_len);
关于string - 为什么从标准输入读取用户输入时我的字符串不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39740798/