186. str::split_inclusive — Split a String and Keep the Separator With Each Chunk
"a\nb\n".split('\n') swallows every newline and hands you a phantom "" at the end. split_inclusive keeps each separator glued to the chunk it belongs to — no ghost element, and you can .concat() straight back to the original.
The split that loses information
The default split is destructive: the matched character is gone, and a trailing separator becomes an empty string.
| |
That phantom empty string is the source of a hundred Stack Overflow questions. You usually paper over it with .filter(|s| !s.is_empty()) or trim_end() before splitting.
split_inclusive keeps the terminator
Each piece keeps the separator that ended it. The trailing newline isn’t an empty string — it’s the end of the last real chunk.
| |
When you actually want this
Reformatting line by line without losing the trailing newline:
| |
No newline added, none lost — every \n is already where it should be.
Works on slices too
[T]::split_inclusive exists with the same shape, taking a predicate instead of a pattern. Useful for batching consecutive items up to a delimiter element.
| |
Reach for split_inclusive whenever the separator is part of the data — line endings, statement terminators, record markers — not noise to throw away.