1

私は2つの文字列を持っています

string str1 = "Hello World !"; // the position of W character is 6
string str2 = "peace";
//...
string result = "Hello peace !"; // str2 is written to str1 from position 6

このような機能はありますか?

string result = str1.Rewrite(str2, 6); // (string, position)


この「HelloWorld !」を編集しました 単なる例です。この文字列に「W」文字が含まれているかどうかはわかりません。私が知っているのはstr1、、、str2position(int)だけです。

4

3 に答える 3

3

ありませんが、拡張メソッドを使用して作成できます。

public static class StringExtensions
{
    public static string Rewrite(this string input, string replacement, int index)
    {
        var output = new System.Text.StringBuilder();
        output.Append(input.Substring(0, index));
        output.Append(replacement);
        output.Append(input.Substring(index + replacement.Length));
        return output.ToString();
    }
}

次に、元の質問に投稿したコードが機能します。

string result = str1.Rewrite(str2, 6); // (string, position)
于 2012-10-18T12:40:14.153 に答える
1

@danludwigsの答えは、コードの理解しやすさの観点からは優れていますが、このバージョンの方が少し高速です。文字列形式(wtf bbq btw :))のバイナリデータを扱っているというあなたの説明は、速度が重要である可能性があることを意味します。バイト配列などを使用する方が文字列を使用するよりも良いかもしれませんが:)

public static string RewriteChar(this string input, string replacement, int index)
{
  // Get the array implementation
  var chars = input.ToCharArray();
  // Copy the replacement into the new array at given index
  // TODO take care of the case of to long string?
  replacement.ToCharArray().CopyTo(chars, index);
  // Wrap the array in a string represenation
  return new string(chars);
}
于 2012-10-18T14:11:27.763 に答える
0

これを行うには多くの方法があります...

私は怠惰なお尻なので、私は行きます:

result = str1.Substring(0, 6) + str2 + str1.Substring(12, 2);

また

result = str1.Replace("World", str2);

私のアドバイスは、Visual Studioで「文字列」を右クリックし、「定義に移動」を選択することです。文字列「class」で使用できるすべてのメソッドが表示されます。

于 2012-10-18T12:38:19.217 に答える