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

标签 rust

我正在尝试使用空格和 , 在 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`

最佳答案

使用闭包:

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

这是基于 String documentation .

关于rust - 如何使用多个参数在 Rust 中拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093878/

相关文章:

pattern-matching - 为什么在尝试匹配元组时会出现类型不匹配的错误?

generics - 如何调用许多不同类型的函数?

rust - 如何使用 Serde 在序列化期间转换字段?

compiler-errors - 为什么使用 f32::consts::E 会给出错误 E0223 但 std::f32::consts::E 不会?

compiler-errors - 如何编译以下 Rust 代码?

Rust 中作为可选函数参数的闭包

rust - 是否可以在没有枚举的情况下将错误原因存储在结构中?

rust - 如何从自定义错误类型中冒出基础错误类型?

rust - DataFusion(Apache Arrow): How to lazily read batches of result?

rust - 什么是 Go 的 select case paradigm for channels in Rust?