どうも、ちょげ(@chogetarou)です。
文字列(string)を1文字ずつに分割する方法を紹介します。
方法

文字列(string)を1文字ずつに分割するには、chars()を使います。
具体的には、「text.chars()
」のように、文字列からchars()を呼び出します。
//text=対象の文字列
let result = text.chars();
上記のchars()は、呼び出した文字列(string)を1文字ずつに分割したイテレータを生成します。
もし、1文字ずつに分割したVec(ベクタ)を取得したい場合は、chars()からcollect()を呼び出します。
//Vec(ベクタ)として取得
let result: Vec<char> = text.chars().collect::<Vec<char>>();
使用例
fn main() {
let text: &str = "Hello,World";
let result: Vec<char> = text.chars().collect::<Vec<char>>();
println!("{:?}", result);
}
出力:
['H', 'e', 'l', 'l', 'o', ',', 'W', 'o', 'r', 'l', 'd']
コメント