How to get the nth char of a string through s.chars() without using 'for loop'?

As we know, strings cannot be indexed.

I can get the chars one by one by using a for loop:

    let hello = String::from("こんにちは");
    println!("{:?}\n{:?}", hello.chars(), hello.bytes());
    for c in hello.chars() {
        println!("{c}");
    }

but how can I can the first one without going into a loop? I tried:

    let first_char=&hello.chars()[0];
    println!("{first_char}");

It got compile errors.

I cannot always rely on a loop to get what I want. How to do that? Thanks.

You can call .next() on the chars iterator.

1 Like

Thanks, but this is only the first one, what if I want get a specific one (n position)?

You can call .nth(n)

1 Like

Thanks, that works!

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.