rustHow to count number of lines in a string in Rust?
To count the number of lines in a string in Rust, you can use the lines()
method of the str
type. This method returns an iterator over the lines of the string. The following example code block shows how to use the lines()
method to count the number of lines in a string:
let s = "This is a string
with multiple lines";
let line_count = s.lines().count();
println!("The string has {} lines", line_count);
The output of the example code is:
The string has 2 lines
The code works as follows:
- The
let s = ...
line creates a string variables
with the valueThis is a string\nwith multiple lines
. - The
let line_count = s.lines().count()
line calls thelines()
method on thes
string, which returns an iterator over the lines of the string. Thecount()
method is then called on the iterator, which returns the number of lines in the string. - The
println!("The string has {} lines", line_count)
line prints the number of lines in the string to the console.
Helpful links
More of Rust
- How to replace a capture group using Rust regex?
- How to implement PartialEq for a Rust HashMap?
- How to push an element to a Rust slice?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to calculate the sum of a Rust slice?
- How to use regex with bytes in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to convert a Rust slice of u8 to a string?
See more codes...