コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】最初に見つかった文字列だけ置換する string.Replace

ソースコード

public static string ReplaceFirst
(
    this string self,
    string      oldValue,
    string      newValue
)
{
    var startIndex = self.IndexOf( oldValue );

    if ( startIndex == -1 ) return self;

    return self
            .Remove( startIndex, oldValue.Length )
            .Insert( startIndex, newValue )
        ;
}

public static string ReplaceFirst
(
    this string      self,
    string           oldValue,
    string           newValue,
    StringComparison comparisonType
)
{
    var startIndex = self.IndexOf( oldValue, comparisonType );

    if ( startIndex == -1 ) return self;

    return self
            .Remove( startIndex, oldValue.Length )
            .Insert( startIndex, newValue )
        ;
}

使用例

Debug.Log( "ギギアル".Replace( "ギ", "ギギ" ) );      // ギギギギアル
Debug.Log( "ギギアル".ReplaceFirst( "ギ", "ギギ" ) ); // ギギギアル