3

Why iterating over the string slice is not possible?

fn main() {
    let text = "abcd";
    for (i, c) in text.iter().enumerate() {
        // ...
    } 
}

gives an error

error[E0599]: no method named `iter` found for reference `&str` in the current scope
 --> src/main.rs:3:24
  |
3 |     for (i, c) in text.iter().enumerate() {
  |                        ^^^^ method not found in `&str`

How do I make the string slice iterable?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Jaebum
  • 1,397
  • 1
  • 13
  • 33
  • 1
    Does this answer your question? [How do you iterate over a string by character](https://stackoverflow.com/questions/22118221/how-do-you-iterate-over-a-string-by-character) – Emoun Oct 09 '21 at 06:54

2 Answers2

19

There is no .iter() method defined for str; perhaps because it is potentially ambiguous. Even in your question, its not clear what exactly you want to iterate over, the characters or the bytes.

  • .bytes() will yield the raw utf-8 encoded bytes
  • .chars() will yield the chars, which are unicode scalar values
  • or maybe .graphemes() from the unicode-segmentation crate which yields substrings for each "user-perceived character"

There are plenty of use-cases for each, just choose which is most appropriate. Playground

use unicode_segmentation::UnicodeSegmentation; // 1.8.0

fn main() {
    let text = "‍♂️"; // browser rendering may vary
    println!("{}", text.bytes().count());         // 17
    println!("{}", text.chars().count());         // 5
    println!("{}", text.graphemes(true).count()); // 1
}
kmdreko
  • 42,554
  • 6
  • 57
  • 106
0

To iterate on a string chars, you can use the chars() method:

fn main() {
    let text = "abcd";
    for (i, c) in text.chars().enumerate() {
       println!("i={} c={}", i, c) 
    } 
}
Joël Hecht
  • 1,766
  • 1
  • 17
  • 18