There have been several times where I want to use
str::split, but I want the splits to include the separator. One question with such a method though is whether the separator should be at the start of the split strings or at the end.
I'd like to propose two functions for
split_prefix. They work like
split, but include the separator at the end or beginning (respectively). Examples showing
let message = "foo\nbar\n\nbaz\n"; let splits: Vec<_> = message.split('\n').collect(); assert_eq!(splits, vec!["foo", "bar", "", "baz", ""]); let splits: Vec<_> = message.split_suffix('\n').collect(); assert_eq!(splits, vec!["foo\n", "bar\n", "\n", "baz\n"]); let splits: Vec<_> = message.split_prefix('\n').collect(); assert_eq!(splits, vec!["foo", "\nbar", "\n", "\nbaz", "\n"]);
I guess you could also argue for
split_terminator_prefix (same as
split_prefix but if there's trailing terminator it is omitted). Or a variant that puts the separators in their own strings (e.g.,
["foo", "\n", "bar", "\n", "\n", "baz", "\n"]). But I'm not interested in those functions. I'm primarily interested in
split_suffix. My use case: I want to separate a string by lines (
'\n'), but I want to keep all the characters in the splits.
I can implement this myself as a crate, but I think others would also find this useful.