How to split a string and still contain pattern

I want to be able to split a string like String::new().split(' ') does, but include the pattern char/&str.
For example.

let string: &str = "helloab:)c"
let split_string: Vec<&str> = expression.split(['a','b','c']).collect();
assert_eq!(split_string, ["hello", "a", "b", ":)", "c"]);

Is there a way to do it with std or do I have to create my own super inefficient way?

Well, I found string.match_indices() but that gives me positions instead, and although I could use that It seems like I might have to write my own function.

It's probably super inefficient, but it works so here it is if anyone needs it.

fn keep_split(string: &str, pat: &[char]) -> Vec<String> {
    let mut output: Vec<String> = Vec::new();
    let mut word: String = String::new();

    for ch in string.chars() {
        if pat.contains(&ch) {
            output.push(word);
            word = String::new();
            output.push(ch.to_string());
        } else {
            word.push(ch)
        }
    }
    if !word.is_empty() {
        output.push(word);
    }
    output
}

This StackOverflow answer has an example of how to do it with match_indices; the only change necessary would be to replace the |c: char| closure with the character slice.

There is split_inclusive

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.