0

Is there an easy way to apply a step during iteration? I have seen a reference to step_by() in the book but I cant seem to get it to work.

For example, to print every-other character of a string I can do this but is there an easier way?

let s1 = "whhaatt".to_string();

for letter in s1.chars().enumerate() {
    let (i, l) = letter;
    if i % 2 == 0 {
        println!("{:?}", l );
    }
}
2
  • Note: chars return code-points, not necessarily what is graphically represented as a single character, hope that's alright with you, Commented Jun 25, 2015 at 13:53
  • 1
    Note: I found the referenced step_by and it is only implemented for Range and RangeFrom. Commented Jun 25, 2015 at 13:56

1 Answer 1

3

The simplest way would be to use the step adaptor from the itertools crate. In this case, you could use s1.chars().step(2).

Aside: Your code does not iterate over "characters"; it iterates over code points. It's quite likely that you want the graphemes method from the unicode-segmentation crate.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, was the syntax for step_by() changed to setp()?
.step_by is only for ranges. .step() is for all iterators (it might be slow because of this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.