Home
Rust
String lines Example
Updated Feb 8, 2023
Dot Net Perls
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.
iter
File
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).
for
Detail Lines() returns an iterator. This means we can call map and collect on the lines, and put the lines in a Vector of strings.
map
collect
String Array
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 8, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen