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/39519833/

相关文章:

rust - 如何返回带有 `&self` 的 future 组合器

C++ While If 条件 y/n 用户选择

c - 字符串数组访问错误

string - awk 全局替换所有出现的字符串

java - 比较和删除 vector 中的相似字符串

c - C 中的十进制值被认为是真的吗?

javascript - 基于条件语句调用具有多个参数的函数

javascript - 将作为字符串从 API 返回的正则表达式转换为 JavaScript 中的有效 RegEx 对象

rust - 我如何在 Rust 中获取 SHA256 的前 4 个字节?

rust - 如何使用toml-rs和serde_derive反序列化两种不同的结构和文件格式?