[Rust]文字列(string)を空白で分割するには?

Rust

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

文字列(string)を空白で分割する方法を紹介します。

スポンサーリンク

方法

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

文字列(string)を空白で分割するには、split_whitespace()を使います。

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

split_whitespace()からcollect::<Vec<T>>()を呼び出します。

//text=対象の文字列, T=文字列の型
let result = text.split_whitespace().collect::<Vec<T>>();

上記のcollect()は、文字列(string)の空白で分割したVec(ベクタ)を取得します。

上記のcollect()は、必ず使う必要はありません。

collect()を使わない場合は、文字列を空白で分割したイテレータが結果となります。

使用例

fn main() {
    let text: &str = "He l lo, Wor ld.";
    
    let result = text.split_whitespace().collect::<Vec<&str>>();
    
    println!("{:?}", result);
}
出力:
["He", "l", "lo,", "Wor", "ld."]

コメント

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