这段代码:
fn main() {
let text = "abcd";
for char in text.chars() {
if char == 'b' {
// skip 2 chars
}
print!("{}", char);
}
// prints `abcd`, but I want `ad`
}
Run Code Online (Sandbox Code Playgroud)
打印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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |