Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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<char> 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.

like image 734
Sarien Avatar asked Dec 15 '17 09:12

Sarien


People also ask

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

To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.

Can you convert a string to a list?

Strings can be converted to lists using list() .

How do I turn a text into a list?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

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

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


2 Answers

Use the chars method on String or str:

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

Here you have a live example

like image 154
Netwave Avatar answered Oct 13 '22 21:10

Netwave


I've already come to this solution:

let chars: Vec<char> = input.chars().collect(); 

In a comment somebody suggested using .split("") but it seems to be implemented in a way that is annoying for this case:

println!("{:?}", "abc".split("").collect::<Vec<&str>>()); 

gives ["", "a", "b", "c", ""]

like image 20
Sarien Avatar answered Oct 13 '22 22:10

Sarien