5

I have this code in Rust:

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

In C, I believe you can just do this:

for (int i = 0; i < strlen(string); ++i) {
    if (string[i] == 't') {
        i += 4;
        continue;
    }
}

How would you implement this in Rust? Thanks.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
dev-gm
  • 63
  • 1
  • 4
  • I'm a rust beginner myself, but maybe [skip](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.skip) works? – lucidbrot Jan 20 '22 at 16:35
  • 1
    Note that the C example iterates over bytes while the Rust example iterates over code points. – Colonel Thirty Two Jan 20 '22 at 16:36
  • One workaround would be to add something like `if skip_count > 0 { skip_count = skip_count - 1; continue; }` in the beginning of the loop. Then in your condition set `skip_count = 4;`. Here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d7e3efe1267025e3239215552d554f09 .Not putting it as answer because there might be some proper solution I am not aware of. – Eugene Sh. Jan 20 '22 at 16:48
  • 1
    Yeah, I could definitely do a workaround like that, but I was just wondering whether there is an idiomatic way to do it with Rust. Also, that requires it to go through the loop an unnecessary amount of times, which seems inefficient. – dev-gm Jan 20 '22 at 16:49

1 Answers1

7

Since string.chars() gives us an iterator, we can use that to create our own loop that gives us controls about the iterator:

let string = "Hello World!";
let mut iter = string.chars();

while let Some(ch) = iter.next() {
    if ch == 'e' {
        println!("Skipping");
        iter.nth(5);
        continue;
    }
    println!("{}", ch);
}

Will output:

H
Skipping
r
l
d
!

Try it online!

0stone0
  • 34,288
  • 4
  • 39
  • 64