如何在Rust中使用多个参数分割字符串?

7
我将尝试使用空格和,来分割一个 Rust 字符串。我尝试了以下代码:
let v: Vec<&str> = "Mary had a little lamb".split_whitespace().collect(); 
let c: Vec<&str> = v.split(',').collect();

结果如下:
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`

可能是如何在Rust中拆分字符串?的重复问题。 - Stargateur
2个回答

12

使用闭包:

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

这基于String文档


7

将包含字符的切片传递给它:

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

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

split 接受一个 Pattern 类型的参数。要查看可以作为参数传递的内容,具体请参见实现者


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接