Chunks() in &str

Hi, I am trying to iterate over every two chars in &str by using chunks. But compile failed. Any suggestion? Thanks!
slice - Rust (rust-lang.org)

fn main() {
    let s = "abcdefg";
    for i in s.chunks(2) {
    }
}
error[E0599]: no method named `chunks` found for reference `&str` in the current scope
 --> src\main.rs:3:16
  |
3 |     for i in s.chunks(2) {
  |                ^^^^^^ method not found in `&str`

chunks is on &[T], not &str.

You might consider using Itertools::tuples:

for (a, b) in s.chars().tuples() {

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cf72b778f987f6420113612c45e00d33

2 Likes

If you convert the string into a slice (likely by not instantiating the input to String in the first place), you could opt for something such as the following:

let iter = slice.windows(2).step_by(2);
//... or 
let iter = slice.chunks_exact(2)

Playground

1 Like

@EdmundsEcho &[char] is generally not a type you want to be working with, and I find it hard to imagine where it would naturally come up (note that you can already collect an iterator of char into a String).

3 Likes

I agree; using chars is awkward and generally unnecessary. However, perhaps in this case, parsing a string, we need the char view of the world to accomplish the task. Note how it avoids using an external lib.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.