我有两个字符串
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)
已编辑
这个“ Hello World !”只是一个例子,我不知道这个字符串中有没有“W”字符,我只知道有:str1, str2, position (整数)
请您参考如下方法:
没有,但您可以使用扩展方法创建一个。
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)
