Split text on several separators
To split text on multiple separators in Rust, you can use the split
method from the str
type. This method allows you to specify a single character separator, but you can use it multiple times to split on different separators. Here's an example:
fn main() {
let text = "Hello, world! This is a sample text.";
let separators = [' ', ',', '!'];
let split_text: Vec<&str> = text.split(separators.as_ref()).collect();
for word in split_text {
println!("{}", word);
}
}
In this example, the text
variable contains the input text that you want to split. The separators
array contains the characters that you want to use as separators. In this case, we are using a space, comma, and exclamation mark as separators.
The split
method is called on the text
variable, passing in the separators
array as an argument. This will split the text at each occurrence of any of the characters in the separators
array.
The result of the split
method is an iterator, so we use the collect
method to collect the iterator into a Vec<&str>
. This will give us a vector of substrings, where each substring is a part of the original text that was separated by one of the specified characters.
Finally, we iterate over the split_text
vector and print each substring.
This will output the following:
Hello
world
This
is
a
sample
text.
Each word or substring is printed on a separate line.