Rust 文字列を置換する

Rust 文字列を置換する

Rustで、文字列を置換するサンプルコードを記述してます。「replace()」か「replacen()」を使用します。Rustのバージョンは1.66.0を使用してます。

環境

  • OS windows11 home
  • rustc 1.66.0

文字列を置換

文字列を置換するには「replace()」と「replacen()」を使用します。違いは置換する数を指定できるかどうかとなります。

文字列.replace("置換したい文字列","置換後の文字列")

文字列.replacen("置換したい文字列","置換後の文字列", 置換する数)

実際に使用してみます。

fn main() {

    let str: String = "mebee".to_string();

    println!("{}", str.replace("e", "a")); // mabaa
    println!("{}", str.replace("ee", "a")); // meba

    println!("{}", str.replacen("e", "a", 1)); // mabee
    println!("{}", str.replacen("e", "a", 2)); // mabae

}

実行結果を見ると、置換されていることが確認できます。

日本語

日本語も、置換されます。

fn main() {

    let str: String = "あああいいうういいあああ".to_string();

    println!("{}", str.replace("あ", "い")); // いいいいいうういいいいい
    println!("{}", str.replace("いい", "う")); // あああううううあああ

}

実行結果