7

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`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Anon
  • 71
  • 1
  • 2
  • Possible duplicate of [How to split a string in Rust?](https://stackoverflow.com/questions/26643688/how-to-split-a-string-in-rust) – Stargateur Apr 30 '18 at 07:58

2 Answers2

12

Use a closure:

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

This is based upon the String documentation.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ben Stern
  • 306
  • 1
  • 9
7

Pass a slice with the chars to it:

fn main() {
    let s = "1,2 3";
    let v: Vec<_> = s.split([' ', ','].as_ref()).collect();

    assert_eq!(v, ["1", "2", "3"]);
}

split takes an argument of type Pattern. To see what concretely you can pass as parameter, see the implementors

Boiethios
  • 38,438
  • 19
  • 134
  • 183