Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in Rust with multiple parameters?

Tags:

rust

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`
like image 310
Anon Avatar asked Apr 30 '18 04:04

Anon


People also ask

How do I split a string into multiple parts?

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.

How do you split string in Rust?

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.

How do you split a string into vector in Rust?

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.

Can split take multiple arguments Javascript?

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.


1 Answers

Use a closure:

let v: Vec<&str> = "Mary had a little lamb."
    .split(|c| c == ',' || c == ' ')
    .collect();

This is based upon the String documentation.

like image 178
Ben Stern Avatar answered Sep 18 '22 19:09

Ben Stern