Created
February 23, 2020 11:33
-
-
Save jamesmcm/b5b2ac4836fd908a7de97e222cd1cb4e to your computer and use it in GitHub Desktop.
split_with_matches.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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