从 io::stdin().read_line() 到 trim '\n' 的更好方法是什么?

What is a better way to trim '\n' from io::stdin().read_line()?

下面的代码对我来说没问题。

let mut buffer = String::new();
io::stdin().read_line(&mut buffer);
buffer = buffer.trim().to_string();

read_line 到 trim '\n' 的 better/correct 方法是什么?

我只看到您的代码中可以改进的一个方面:您分配了 两个 字符串来读取一行。第一次分配发生在将行读入 buffer 时,第二次分配发生在 to_string().

根据上下文,有几种方法可以避免这种情况。最简单的方法是简单地避免调用 to_string,并继续使用 &str 而不是 String。如果这对你不起作用,你也可以编写自己的函数来 trim 字符串末尾的换行符:

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}

这不等同于原始代码中的 trim(),因为它只从字符串的末尾删除换行符,而不是从字符串的任何一端删除任意空格。

另一种选择是使用 lines() 迭代器从 stdin 生成没有终止换行符的行:

use std::io::{BufRead};
let stdin = std::io::stdin();
for line in stdin.lock().lines() {
    let line = line?;   // line is a Result<String, io::Error>
}