如何从迭代器循环内部跳过n个项目? [英] How to skip n items from inside of a iterator loop?
本文介绍了如何从迭代器循环内部跳过n个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码:
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
.我怎么做?
prints abcd
, but I want to skip 2 chars if b
was found, so that it prints ad
. How do I do that?
我试图将迭代器放入循环外的变量中,并在循环内操纵该迭代器,但借阅检查器不允许这样做.
I tried to put the iterator into a variable outside the loop and manipulate that iterator within the loop, but the Borrow Checker doesn't allow that.
推荐答案
AFAIK,使用for
循环无法做到这一点.您将需要手工对其进行除糖:
AFAIK you can't do that with a for
loop. You will need to desugar it by hand:
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);
}
这篇关于如何从迭代器循环内部跳过n个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文