[Rust]文字列(string)を特定の文字ごとに分割するには?

Rust

どうも、ちょげ(@chogetarou)です。

文字列(string)を特定の文字ごとに分割する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

文字列(string)を特定の文字ごとに分割するには、spilt()を使います。

まず、文字列からsplit()を呼び出します。

そして、split()の引数に区切り文字を指定します。

//text=対象の文字列, sep=区切り文字
let result = text.split(sep);

上記のsplit()は、呼び出した文字列(string)を引数の文字ごとに分割したイテレータを生成します。

もし、分割した結果をVec(ベクタ)として取得したい場合は、collect()を使います。

let result: Vec<&str> = text.split(sep).collect::<Vec<&str>>();

使用例

fn main() {
    let text: &str = "He,llo,Worl,d";
    
    let result: Vec<&str> = text.split(",").collect::<Vec<&str>>();
    
    println!("{:?}", result);
}
出力:
["He", "llo", "Worl", "d"]

コメント

タイトルとURLをコピーしました