HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How do I convert a string to a list of chars?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howcharsconvertliststring

Problem

Since a string supports iteration but not indexing, I would like to convert a string into a list of chars. I have "abc" and I want ['a', 'b', 'c'].

It can be any type as long as I can index into it. A Vec or a [char; 3] would be fine, other ideas would also be interesting!

Faster would be better since I am dealing with very long strings. A version that is more efficient when assuming that the string is ASCII would also be cool.

Solution

Use the chars method on String or str:

fn main() {
    let s = "Hello world!";
    let char_vec: Vec = s.chars().collect();
    for c in char_vec {
        println!("{}", c);
    }
}


Here you have a live example

Code Snippets

fn main() {
    let s = "Hello world!";
    let char_vec: Vec<char> = s.chars().collect();
    for c in char_vec {
        println!("{}", c);
    }
}

Context

Stack Overflow Q#47829646, score: 100

Revisions (0)

No revisions yet.