Reading a line in txt, compare and jump?

Hi, how compare a string against txt file line ??. Thanks

let reader = fs::read_to_string(filename)
                                    .expect("Except: file info.txt not exist");
    
            let mut lines = reader.lines();
    
            // skip first line "\u{feff}"
            //lines.next();
            if lines == "\u{feff}" {
                lines.next();
            }

:face_with_spiral_eyes:
ERROR:
error[E0369]: binary operation == cannot be applied to type std::str::Lines<'_>
--> src/main.rs:1030:22
|
1030 | if lines == "\u{feff}" {
| ----- ^^ ---------- &str
| |
| std::str::Lines<'_>

lines is a struct that iterates over lines of reader, it doesn't make sense to compare it to a string. If you want the next line, call lines.next(). You can then use it, for example like this

if let Some(line) = lines.next() {
    if line == "\u{feff}" {
        // ..
    }
}

But if you just want to skip the first line if it's "\u{feff}", you could do something like this

let mut line = lines.next();
if line == Some("\u{feff}") {
    // set `line` to the next line instead
    line = lines.next();
}
3 Likes

Or use Peekable::next_if_eq:

let mut lines = reader.lines().peekable();

// consumes the next line only if it is equal to "\u{feff}"
lines.next_if_eq(&"\u{feff}");
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.