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.rs90 chars5 lines
This will output:
main.rs37 chars4 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.rs101 chars5 lines
This will output:
main.rs28 chars3 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.rs106 chars4 lines
This will output:
main.rs22 chars2 lines
gistlibby LogSnag