【问题标题】:How to split a string in Rust with multiple parameters?如何在 Rust 中拆分具有多个参数的字符串?
【发布时间】:2018-04-30 04:15:52
【问题描述】:

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


【解决方案1】:

使用闭包:

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

这是基于String documentation

【讨论】:

    【解决方案2】:

    将带有chars 的切片传递给它:

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

    split 接受Pattern 类型的参数。要查看具体可以作为参数传递的内容,请参阅the implementors

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2014-12-25
      • 2022-10-15
      • 1970-01-01
      • 2012-12-27
      • 2010-10-13
      • 1970-01-01
      • 2017-11-03
      相关资源
      最近更新 更多