Skip to content

Instantly share code, notes, and snippets.

@jamesmcm
Created February 23, 2020 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmcm/b5b2ac4836fd908a7de97e222cd1cb4e to your computer and use it in GitHub Desktop.
Save jamesmcm/b5b2ac4836fd908a7de97e222cd1cb4e to your computer and use it in GitHub Desktop.
split_with_matches.rs
fn split_with_matches<'a, F>(s: &'a str, f: F) -> Vec<&'a str>
where
F: Fn(char) -> bool,
{
let mut out: Vec<&'a str> = Vec::new();
let mut prevpos: usize = 0;
for (pos, c) in s.bytes().enumerate() {
if f(c as char) {
if prevpos != pos {
out.push(&s[prevpos..pos]);
}
out.push(&s[pos..pos + 1]);
prevpos = pos + 1;
}
}
if prevpos != s.len() {
out.push(&s[prevpos..]);
}
out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment