Str Split Inclusive Terminator
Split text with split_inclusive so each piece keeps its terminator, then contrast the result with lines and a custom predicate.
Code
fn main() {
let log = "start\nwork\nend";
// split_inclusive keeps the terminator on each yielded piece
for (index, part) in log.split_inclusive('\n').enumerate() {
println!("{index}: {part:?}");
}
// a predicate can mark any character as the boundary
let chunks: Vec<&str> = "a,b;c".split_inclusive(|c| c == ',' || c == ';').collect();
println!("chunks: {chunks:?}");
// lines removes the terminator, so the pieces differ
let without: Vec<&str> = log.lines().collect();
println!("lines: {without:?}");
println!("inclusive count: {}", log.split_inclusive('\n').count());
// the final piece has no terminator when the input lacks one
let tail: Vec<&str> = "one\ntwo".split_inclusive('\n').collect();
println!("tail: {tail:?}");
}How it works
Str Split Inclusive Terminator is built around the function main.
The one repetition in this snippet is the loop for (index, part) in log.split_inclusive('\n').enumerate().
Watch out for
- Ready as-is on a bare install of the language.
Using it
Running the file prints labeled results such as chunks:, lines:, inclusive count: — each operation’s effect is visible in the output.
Key statements
let chunks: Vec<&str> = "a,b;c".split_inclusive(|c| c == ',' || c == ';').collect();
let tail: Vec<&str> = "one\ntwo".split_inclusive('\n').collect();
let without: Vec<&str> = log.lines().collect();
Interactive Tools for This Topic
FAQ
- What does Str Split Inclusive Terminator print when run?
- Running the file directly is enough — expect labeled output lines such as `chunks:`, `lines:`, `inclusive count:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.