What is the string.lines() method in Rust?
Overview
The string.lines() method in Rust returns an iterator over the lines of a string, and enables us to perform various operations on each line.
Syntax
string.lines()
Syntax for lines() method
Parameters
string: This is the string on which we want to apply the string.lines() method.
Return value
The value returned is an iterator containing the lines of the string.
Example
In the code snippet below, we created some strings and then printed each line of the string.
fn main() {// create some stringslet str1 = "Rust is very \ninteresting.It is the best!";let str2 = "Educative \nis the best";// print substrings of stringfor line in str1.lines() {println!("{}", line);}// print each line of the stringfor line in str2.lines() {println!("{}", line);}}
Explanation
In the code above:
- Line 3: We created a string that has some lines. The first line ends with the escape character
\n. The second line starts and ends withinterestingand the third line ends with some spaces andIt is the best!. - Line 5: We created another string similar to line 3.
- Lines 8 and 13: We use the
lines()method to get the iterators containing the lines of each of the strings we created. Then, with thefor inloop, we print each line of string to the console.