Lines. 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.
Lines example. 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).
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"]
Filter. 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.
Here We use filter and filter out all lines except those that start with the lowercase letter B.
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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.