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.
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.
Strings can be converted to lists using 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.
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.
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
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", ""]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With