gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:10:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com