string - 从 io::stdin().read_line() 中修剪 '\n' 的更好方法是什么?

标签 string rust newline

<分区>

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

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

read_line 中修剪 '\n' 的更好/正确方法是什么?

最佳答案

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

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

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

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

另一种选择是使用 lines() 迭代器,它从标准输入中生成没有终止换行符的行:

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>
}

关于string - 从 io::stdin().read_line() 中修剪 '\n' 的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54395227/

相关文章:

rust - 即使我正在发送换行符,TCP 回显服务器也从不回复

C++ 到 Cuda 转换/字符串生成和比较

python - Python Doctest 中的特殊字符和换行符

iterator - 如何编写返回对自身的引用的迭代器?

python - 如何在每行末尾添加一个\n

git - 尽管出现 "No newline at end of file"警告,如何在 git gui 中逐行暂存

emacs - 如何强制 emacs 使用\n 而不是\r\n

java - 为什么 str == str.intern() for StringBuilder using append or not different 的结果?

java - 用于访问 JDK 8 HotSpot JVM 中的字符串池内容的实用程序

rust - 为什么有必要添加冗余特征边界,即使我的特征使用那些相同的特征作为边界?