gpt4 book ai didi

rust - 如何从迭代器循环内部跳过 n 个项目?

转载 作者:行者123 更新时间:2023-12-04 23:35:31 34 4
gpt4 key购买 nike

这段代码:

play

fn main() {
let text = "abcd";

for char in text.chars() {
if char == 'b' {
// skip 2 chars
}
print!("{}", char);
}
// prints `abcd`, but I want `ad`
}

版画 abcd ,但如果 b,我想跳过 2 个字符被发现,所以它打印 ad .我怎么做?

我试图将迭代器放入循环外的变量中并在循环内操作该迭代器,但借用检查器不允许这样做。

最佳答案

AFAIK 你不能用 for 做到这一点环形。您需要手动对其进行脱糖:

let mut it = text.chars();
while let Some(char) = it.next() {
if char == 'b' {
it.nth(1); // nth(1) skips/consumes exactly 2 items
continue;
}
print!("{}", char);
}

Playground

关于rust - 如何从迭代器循环内部跳过 n 个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59045408/

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