Editor's note: This code example is from a version of Rust prior to 1.0 when many iterators implemented
Copy
. Updated versions of this code produce a different errors, but the answers still contain valuable information.
I'm trying to write a function to split a string into clumps of letters and numbers; for example, "test123test"
would turn into [ "test", "123", "test" ]
. Here's my attempt so far:
pub fn split(input: &str) -> Vec<String> {
let mut bits: Vec<String> = vec![];
let mut iter = input.chars().peekable();
loop {
match iter.peek() {
None => return bits,
Some(c) => if c.is_digit() {
bits.push(iter.take_while(|c| c.is_digit()).collect());
} else {
bits.push(iter.take_while(|c| !c.is_digit()).collect());
}
}
}
return bits;
}
However, this doesn't work, looping forever. It seems that it is using a clone of iter
each time I call take_while
, starting from the same position over and over again. I would like it to use the same iter
each time, advancing the same iterator over all the each_time
s. Is this possible?