Search code examples
stringfile-ioruststring-parsing

Why does my line from BufReader::lines not match?


I am trying to parse a text file and find if a string is equal to current line I am on using BufReader:

let mut chapter = String::from("Chapter 1\n");

//open file
let file = File::open("document.txt")?;
let reader = BufReader::new(file);

for line in reader.lines() {
    if chapter.eq(&line.unwrap()) {
        println!("chapter found!");
    }
}

However, the if statement never returns true. How can I properly convert line from reader.lines() into a way I can find a match?


Solution

  • From the documentation of ReadBuf::lines:

    Each string returned will not have a newline byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.

    Remove the \n from your search string:

    let mut chapter = String::from("Chapter 1");
    

    There's no reason to allocate the String here. A number of other changes:

    use std::{
        fs::File,
        io::{self, BufRead, BufReader},
    };
    
    fn example() -> io::Result<()> {
        let chapter = "Chapter 1";
    
        let file = File::open("document.txt")?;
        let reader = BufReader::new(file);
    
        for line in reader.lines() {
            if chapter == line.unwrap() {
                println!("chapter found!");
            }
        }
    
        Ok(())
    }
    

    See also: