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.
string.lines()
string
: This is the string on which we want to apply the string.lines()
method.
The value returned is an iterator containing the lines of the string.
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);}}
In the code above:
\n
. The second line starts and ends with interesting
and the third line ends with some spaces and It is the best!
.lines()
method to get the iterators containing the lines of each of the strings we created. Then, with the for in
loop, we print each line of string to the console.