如何循环跳转多次?

dev*_*-gm 5 string loops skip rust

我在 Rust 中有这样的代码:

for ch in string.chars() {
    if ch == 't' {
        // skip forward 5 places in the string
    }
}
Run Code Online (Sandbox Code Playgroud)

在C语言中,我相信你可以这样做:

for ch in string.chars() {
    if ch == 't' {
        // skip forward 5 places in the string
    }
}
Run Code Online (Sandbox Code Playgroud)

你会如何在 Rust 中实现这个?谢谢。

0st*_*ne0 7

既然string.chars()给了我们一个迭代器,我们可以用它来创建我们自己的循环,让我们可以控制迭代器:

\n
let string = "Hello World!";\nlet mut iter = string.chars();\n\nwhile let Some(ch) = iter.next() {\n    if ch == \'e\' {\n        println!("Skipping");\n        iter.nth(5);\n        continue;\n    }\n    println!("{}", ch);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

将输出:

\n
H\nSkipping\nr\nl\nd\n!\n
Run Code Online (Sandbox Code Playgroud)\n
\n

在线尝试一下!

\n