8

c# に sql function と同等の関数があるかどうかを知る必要がありますstuff。これは、指定された開始と長さに基づいて入力文字列を元の文字列に置き換えます。

サンプルを追加するために編集:

select stuff('sad',1,1'b')

select stuff(original string, start point, length,input string)

出力は次のようになります"bad".

4

5 に答える 5

8

これを行うための組み込みメソッドはありませんが、拡張メソッドを作成できます。

static class StringExtensions
{
    public static string Splice(this string str, int start, int length,
                                string replacement)
    {
        return str.Substring(0, start) +
               replacement +
               str.Substring(start + length);
    }

}

使用法は次のとおりです。

string sad = "sad";
string bad = sad.Splice(0, 1, "b");

C# の文字列の最初の文字は、SQL の例のように 1 ではなく、0 であることに注意してください。

もちろん、必要に応じてメソッドを呼び出すこともできますがStuff、おそらくSplice名前の方が少し明確です (ただし、あまり頻繁には使用されません)。

于 2013-04-12T10:06:15.933 に答える
1

string.replaceとを組み合わせた拡張メソッドを作成できますstring.insert

public static string Stuff(this string str, int start , int length , string replaceWith_expression)
{
    return str.Remove(start, length).Insert(start, replaceWith_expression);
}
于 2013-04-12T10:06:15.200 に答える
0

C# にはそのような関数はありませんが、簡単に記述できます。私の実装はゼロベースであることに注意してください (最初の文字のインデックスは 0 です):

string input = "abcdefg";
int start = 2;
int length = 3;
string replaceWith = "ijklmn";
string stuffedString = input.Remove(start, length).Insert(start, replaceWith);
// will return abijklmnfg

関数を使いやすくする拡張メソッドを作成することもできます。

public static class StringExtensions
{
    public static string Stuff(this string input, int start, int length, string replaceWith)
    {
        return input.Remove(start, length).Insert(start, replaceWith);
    }
}

使用法:

string stuffed = "abcdefg".Stuff(2, 3, "ijklmn");
于 2013-04-12T10:06:59.450 に答える