track newlines in a string in rust

To track newlines in a string in Rust, you can split the string on newline characters using the split method, which returns an iterator that yields substrings between the newline characters. Here's an example:

main.rs
let s = "hello\nworld\n";
for line in s.split('\n') {
    println!("line: '{}'", line);
}
90 chars
5 lines

This will output:

main.rs
line: 'hello'
line: 'world'
line: ''
37 chars
4 lines

Note that the empty string at the end is because the string ends with a newline character. If you don't want the empty string, you can use split_terminator instead:

main.rs
let s = "hello\nworld\n";
for line in s.split_terminator('\n') {
    println!("line: '{}'", line);
}
101 chars
5 lines

This will output:

main.rs
line: 'hello'
line: 'world'
28 chars
3 lines

Alternatively, if you want to count the number of newline characters in the string, you can use the matches method, which returns an iterator over the matches of a pattern. For example:

main.rs
let s = "hello\nworld\n";
let count = s.matches('\n').count();
println!("number of newlines: {}", count);
106 chars
4 lines

This will output:

main.rs
number of newlines: 2
22 chars
2 lines

gistlibby LogSnag