Often a string
in Rust has multiple lines of data—each part is separated by a "\n" character. The lines()
iterator helps us parse these strings.
With lines, we can test or print out each individual line. Or we can use map, filter or collect on the resulting iterator for more power.
This code introduces a string
that has 2 newlines separating 3 lines. By calling lines()
in a for
-loop, we print each part (the newline delimiters are not included).
Lines()
returns an iterator. This means we can call map and collect on the lines, and put the lines in a Vector
of strings.fn main() { let data = "a\n b\n c"; // Loop over and print the lines. for line in data.lines() { println!("{line}"); } // Get the lines, uppercase them, and put them in a vector. let all_lines = data.lines().map(|x| x.to_uppercase()).collect::<Vec<String>>(); println!("{:?}", all_lines); }a b c ["A", " B", " C"]
Suppose you have a string
that has many lines in it, and you just want to use some of them. We can use filter()
on the Lines iterator.
fn main() { let data = "blue\nbird\nfrog"; // Get lines, and filter the lines. // Only print lines starting with a certain letter. for line in data.lines().filter(|x| x.starts_with('b')) { println!("{line}"); } }blue bird
If we have a string
containing multiple lines, and want to loop over them, the lines()
iterator is ideal. It can be used on str
or String
types.