如何将字符串转换为字符列表?
问题描述:
由于字符串支持迭代但不支持索引,我想将字符串转换为字符列表.我有 "abc"
并且我想要 ['a', 'b', 'c']
.
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']
.
它可以是任何类型,只要我可以对其进行索引.一个 Vec
或一个 [char;3]
没问题,其他想法也很有趣!
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!
更快会更好,因为我正在处理很长的字符串.假设字符串是 ASCII 时效率更高的版本也很酷.
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.
答
在 String
或 str
上使用 chars
方法:
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);
}
}
这里有一个现场示例