gpt4 book ai didi

string - 未找到 str 的匹配方法

转载 作者:行者123 更新时间:2023-11-29 08:30:47 26 4
gpt4 key购买 nike

我正在使用 rayon对文本执行并行迭代并尝试输出包含特定字符的字符串。我正在使用 matches() : playground

use rayon::prelude::*;

fn main() {
let text =
"Some are born great, some achieve greatness, and some have greatness thrust upon them."
.to_string();
check(text, 's');
}

fn check(text: String, ch: char) {
let words: Vec<_> = text.split_whitespace().collect();
let words_with_ch: Vec<_> = words.par_iter().map(|ch| words.matches(ch)).collect();
println!(
"The following words contain the letter {:?}: {:?}",
ch, words_with_ch
);
}

但它显示错误:

error[E0599]: no method named `matches` found for type `std::vec::Vec<&str>` in the current scope
--> src/main.rs:12:65
|
12 | let words_with_ch: Vec<_> = words.par_iter().map(|ch| words.matches(ch)).collect();
| ^^^^^^^

如何解决这个编译错误?

最佳答案

正如@zerkms 所建议的,filter() 将是一个很好的函数来解决这个问题。

过滤器在迭代器上工作。 split_whitespace() 创建迭代器,然后可以将其传递给 filter()。

fn main() {
let text =
"Some are born great, some achieve greatness, and some have greatness thrust upon them."
.to_string();
check(text, 's');
}

fn check(text: String, ch: char) {
let words_with_ch: Vec<_> = text
.split_whitespace()
.filter(|w| w.contains(ch))
.collect();
println!(
"The following words contain the letter {:?}: {:?}",
ch, words_with_ch
);
}

关于string - 未找到 str 的匹配方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58551133/

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