【发布时间】:2022-01-12 01:21:38
【问题描述】:
如何在 Rust 中完全删除一行?不只是用空行替换它。
在Rust中,当你从文件中删除一行时,以如下代码为例:
let mut file: File = File::open("file.txt").unwrap();
let mut buf = String::from("");
file.read_to_string(&mut buf).unwrap(); //Read the file to a buffer
let reader = BufReader::new(&file);
for (index, line) in reader.lines().enumerate() { //Loop through all the lines in the file
if line.as_ref().unwrap().contains("some text") { //If the line contains "some text", execute the block
buf = buf.replace(line.as_ref().unwrap(), ""); //Replace "some text" with nothing
}
}
file.write_all(buf.as_bytes()).unwrap(); //Write the buffer back to the file
file.txt:
random text
random text
random text
some text
random text
random text
当你运行代码时,file.txt 变成这样:
random text
random text
random text
random text
random text
不仅仅是
random text
random text
random text
random text
random text
有什么方法可以完全删除该行而不是将其留空?像某种特殊字符?
【问题讨论】: