the content of the file looks like as below:
There are 3 parts above and each one is seperated by a blank line, and sometimes there should be 5 or more parts. I jsut want to extract the last part whatever how many parts in all.
In the example I just want to get the 3 lines which contains 'c'.
One thing you can do is to read the full file into memory with
std::fs::read_to_string(), split it into parts with
split("\n\n"), then use the
last() method all iterators get for free to extract the last part.
let text = std::fs::read_to_string("input.txt").expect("read failed");
let last_part = text.split("\n\n")
.expect("The file had no parts");
I threw in the
filter() so we'll automatically trim away trailing whitespace and drop any "empty" segments (e.g. if the file ended with an empty line).
Note that Michael's approach, thought quite simple, requires reading the entire file. You can instead seek to the end of the file and read out chunks, checking if they contain the pattern
\n\n, until you find one or reach the start of the file. Note that reading out chunks like that can split a UTF-8 code point, you have to do all your work using
Vec<u8> before converting to a
String at the end.