string - 为什么从标准输入读取用户输入时我的字符串不匹配?

标签 string rust conditional-statements user-input

我正在尝试获取用户输入并检查用户输入的是“y”还是“n”。令人惊讶的是,在下面的代码中,ifif 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/46641279/

相关文章:

java - 字符串与方法重复

python - 使用 python 从 .txt 文件中的字符串中提取数字时出现 "Value error: Mixing iteration and read methods would lose data "消息

C++将字符串数组的元素存储到变量中

string - 如何将大十六进制字符串转换为十进制字符串?

websocket - tokio_tungstenite::WebSocketStream 的 split() 方法在哪里实现?

templates - Chef 模板 - 有条件地插入文本 block

arrays - 用matlab数组中的字符串替换数字

rust - 如何使用闭包而不是特征?

mysql - SQL-Query 在应该返回一个的地方返回 2 个返回值

java - if 语句中可以有两个条件吗