Search code examples
stringrustsplit

How do I split a string using multiple different characters as delimiters?


What is the most rusty/current way in (latest Rust) to do a basic and efficient string slit using multiple different possible split characters, i.e. convert:

"name, age. location:city"

into:

["name", "age", "location", "city"]

I understand that we could use a regexp to do this, but this code will be used in log processing and is used on a computer that is cpu/memory bound so I'd prefer to avoid regexp if possible.


Solution

  • str::split accepts a generic splitting Pattern, which can be one of various different things. In particular, it can be a closure deciding whether a character is a delimiter, thus giving us full control while allowing us to take advantage of helper functions in char.

    let value = "name, age. location:city";
    let parts: Vec<_> = value
        .split(|c: char| c.is_ascii_punctuation() || c.is_ascii_whitespace())
        .filter(|p| !p.is_empty())
        .collect();
    assert_eq!(&parts[..], &["name", "age", "location", "city"]);
    

    Playground

    See also: How do I split a string in Rust?