split text on multiple separators and put into a list
To split a text on multiple separators in Rust and put the result into a list, you can use the split()
method from the str
type. This method allows you to specify a pattern as the separator. You can use the |
operator to specify multiple separators.
Here's an example:
fn main() {
let text = "Hello,world|foo-bar+baz";
let separators = ['-', '|', '+'];
let result: Vec<&str> = text.split(|c| separators.contains(&c)).collect();
println!("{:?}", result);
}
In this example, the text is split on the characters -
, |
, and +
. The split()
method takes a closure as an argument, which checks if the current character is one of the separators. The collect()
method is then used to collect the split parts into a vector of string slices (&str
).
The output of the above code will be:
["Hello,world", "foo", "bar", "baz"]
Each part of the split text is stored as an element in the resulting vector.
I hope this helps! Let me know if you have any further questions.