2016年2月25日木曜日

C#の文字列の指定位置を置換する

C#の文字列で一部を置換したかったのだけど、欲しい機能が無いっぽいので作ってみた。

やりたいこと
入力: "012345679", 2, "ABC"
出力: "01ABC56789"

とりあえず拡張メソッドで作った。"0123456789".Replace(2, "ABC") で"01ABC56789"が出力される(はず)。動作チェックはあんまりしてないので間違ってるかも。


public static string Replace(this string Before, int Start, string Insert)
{
    if (string.IsNullOrEmpty(Insert))
    {
        return (Before);
    }

    if (Start < 0)
    {
        Insert = Insert.Substring(-Start);
        Start = 0;
    }

    {
        int hoge = Before.Length - (Start + Insert.Length);
        if (hoge < 0)
        {
            Insert = Insert.Substring(0, Insert.Length + hoge);
        }
    }

    string s1 = Before.Substring(0, Start);
    string s2 = Before.Substring(Start + Insert.Length);

    return (s1 + Insert + s2);
}

0 件のコメント:

コメントを投稿