• notice
  • Congratulations on the launch of the Sought Tech site

How to skip forward multiple times in a loop?

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 do this: p>

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

How would you implement this in Rust? Thanks.

uj5u.com enthusiastic netizens replied:

becausestring.chars() gives us an iterator that we can use to create our own loops and lets us control 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!

Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+