I am trying to split a string in Rust using both whitespace and ,
. I tried doing
let v: Vec<&str> = "Mary had a little lamb".split_whitespace().collect();
let c: Vec<&str> = v.split(',').collect();
The result:
error[E0277]: the trait bound `for<'r> char: std::ops::FnMut<(&'r &str,)>` is not satisfied
--> src/main.rs:3:26
|
3 | let c: Vec<&str> = v.split(',').collect();
| ^^^^^ the trait `for<'r> std::ops::FnMut<(&'r &str,)>` is not implemented for `char`
error[E0599]: no method named `collect` found for type `std::slice::Split<'_, &str, char>` in the current scope
--> src/main.rs:3:37
|
3 | let c: Vec<&str> = v.split(',').collect();
| ^^^^^^^
|
= note: the method `collect` exists but the following trait bounds were not satisfied:
`std::slice::Split<'_, &str, char> : std::iter::Iterator`
`&mut std::slice::Split<'_, &str, char> : std::iter::Iterator`
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
To split a string slice or type &str in Rust, use the split() method to create an iterator. Once the iterator is generated, use a for loop to access each substring to apply any additional business logic.
Use the split() String Method in Rust The collect() method can store the result returned by split() in the form of a vector. The above example splits the string words whenever it finds a comma (,) . The below example uses the split() method to separate the strings based on the space.
To split a string with multiple characters, you should pass a regular expression as an argument to the split() function. You can use [] to define a set of characters, as opposed to a single character, to match.
Use a closure:
let v: Vec<&str> = "Mary had a little lamb."
.split(|c| c == ',' || c == ' ')
.collect();
This is based upon the String documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With