1

I can split a &str like so:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

Is there a way I can split a &str while retaining the elements split over in the iterator? For example:

let v: Vec<&str> = "Mary had a little lamb".split_retain(' ').collect();
assert_eq!(v, ["Mary", " ", "had", " ", "a", " ", "little", " ", "lamb"]);

This iter isn't very useful when we are only splitting over a single char, but it becomes useful when we have a more complex split such as:

let mut iter = some_str.split(|c: char| c.is_whitespace() || c == ':' || c == ',' || c == '(' || c == ')')
HiDefender
  • 2,088
  • 2
  • 14
  • 31
  • 1
    If you want a kind of lexer, do not do like that. There are some good crates that do a great job at making this. – Boiethios Dec 16 '17 at 17:24
  • I haven't found a function in `std` that does this, but you might be able to build it yourself using [`str::match_indices`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.match_indices). – Francis Gagné Dec 16 '17 at 17:50

0 Answers0