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

相关文章:

java - 如何在Java中将字符串转换为0x十六进制格式?

Javascript 匹配以从 URL 中删除部分文件名 - 替换最后一次出现

rust - 为什么我的变量在调试时会重复并且有时会损坏?

rust - 为什么从 TcpStream 更改为特征会导致 "cannot borrow immutable borrowed content as mutable"?

javascript - 如何处理 JavaScript 条件语句中可为 null 的对象

javascript - JS 字符串 : Replace with index in regex

c++ - char = 0 在 c++ 中使用 XOR

rust - 有没有一种方法可以注释一个在rust中采用可选闭包的函数?

python - 基于动态列表python的for循环

jQuery 条件问题