I want to split a string on certain conditions (in this case if a char doesn't match its predecessor), but I do not want to remove the char it matches (like str::split does).
Ascii only (in fact, only digits), so no fancy unicode
If possible without any allocation in between.
However, I don't think this problem particularly fits the notion of "split on a specific character", I'd try to reduce it to something else. Or even just implement it manually (playground).
@H2CO3 nice one. I always forget that using a struct and implementing Iterator for it might be easier, than using a custom iterator with e.g. std::iter::from_fn. Thanks for that!
In particular I like the mem::replace which I haven't had and used a temp variable instead, which is very ugly.
Just two nitpicks and formatting:
impl<'a> Iterator for ExtractConsecutive<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
let fst = self.string.chars().next()?;
for (i, ch) in self.string.char_indices() {
if ch != fst {
let (head, tail) = self.string.split_at(i);
self.string = tail;
return Some(head);
}
}
Some(mem::replace(&mut self.string, ""))
}
}