如何从迭代器循环内部跳过n个项目? [英] How to skip n items from inside of an iterator loop?

查看:37
本文介绍了如何从迭代器循环内部跳过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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆