2

I have a file called a_file.txt and i want to read it like so and filter out the string "help me" from each line in that file:

fn main() -> std::io::Result<()> {
    let _s: String = std::fs::read_to_string("a_file.txt")?
        .lines()
        .filter(|line| line.contains("help me"))
        .map(|s| s.to_string())
        .collect();
    Ok(())
}

The map function here makes it so that collect() returns a String not a &str.

This code returns the text but it seems to have removed the \n. I assume this happens because the lines() function consumes the \n to make an iterator.

How do I retain the \ns? I want to remove the specified string from each line so I have to use the lines() function.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
theBigCheese88
  • 442
  • 4
  • 16
  • I am sorry, filter or filter out? –  Oct 14 '19 at 15:44
  • 1
    It looks like your question might be answered by the answers of [Iterate over lines in a string, including the newline characters](https://stackoverflow.com/q/40455997/155423) or [What's an idiomatic way to print an iterator separated by spaces in Rust?](https://stackoverflow.com/q/36941851/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Oct 14 '19 at 15:48
  • 2
    Or easy but bad solution -> modify your map like this `.map(|s| s.to_string() + "\n")` – Ömer Erden Oct 14 '19 at 15:51
  • 3
    I'd use `.fold(String::new(), |s, l| s + l + "\n")` instead of `.map` and `.collect`. – Shepmaster Oct 14 '19 at 15:57

0 Answers0