[Rust]文字列(string)の特定の文字を置換するには?

Rust

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

文字列(string)の特定の文字を置換する方法を紹介します。

スポンサーリンク

方法

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

文字列(string)の特定の文字を置換するには、replace()を使います。

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

そして、replace()の第1引数に置換する文字、第2引数に置換後の文字を指定します。

//text=対象の文字列, old=置換する文字, new=置換後の文字
let result: String = text.replace(old, new);

上記のreplace()は、呼び出した文字列(string)の第1引数の文字を第2引数の文字に置換した文字列を生成します。

replace()は、指定された文字を全て置換します。

もし、置換する回数に制限をかけたい場合は、replacen()を使います。

具体的には、replacen()の第3引数に置換する回数を指定します。

//count=置換する回数
let result: String = text.replacen(old, new, count);

使用例

fn main() {
    let text: &str = "H-e-l-l-o,W-o-r-l-d.";
    
    let result: String = text.replace("-", ",");
    
    println!("{}", result);
}
出力:
H,e,l,l,o,W,o,r,l,d.

コメント

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