如何覆盖字符串?例子:
string text = "abcdefghijklmnopqrstuvwxyz".OverwriteWith("hello world", 3);
// text == "abchello worldopqrstuvwxyz"
当然这种方法是不存在的。但
- .NET Framework 中有内置的东西吗?
- 如果没有,我怎样才能有效地将一个字符串写入另一个字符串?
你只需要使用类似String.Remove
的String.Insert
方法;
string text = "abcdefghijklmnopqrstuvwxyz";
if(text.Length > "hello world".Length + 3)
{
text = text.Remove(3, "hello world".Length).Insert(3, "hello world");
Console.WriteLine(text);
}
输出将是;
abchello worldopqrstuvwxyz
这里有一个DEMO。
请记住,字符串是.NET 中的不可变类型。你不能改变它们。即使你认为你改变了它们,你实际上也创建了一个新的字符串对象。
如果您想使用可变字符串,请查看StringBuilder
class。
这个类表示一个类似字符串的对象,它的值是一个可变的字符序列。该值被认为是可变的,因为一旦创建它就可以通过附加、删除、替换或插入字符来修改它。
简短的回答,你不能。字符串是不可变的类型。这意味着一旦它们被创建,它们就不能被修改。
如果你想在内存中操作字符串,c++ 方式,你应该使用 StringBuilder。
您可以尝试此解决方案,这可能会对您有所帮助..
var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2); //Used to Remove the
aStringBuilder.Replace(); //Write the Required Function in the Replace
theString = aStringBuilder.ToString();
参考:点这里!!
你想要的是一个扩展方法:
static class StringEx
{
public static string OverwriteWith(this string str, string value, int index)
{
if (index + value.Length < str.Length)
{
// Replace substring
return str.Remove(index) + value + str.Substring(index + value.Length);
}
else if (str.Length == index)
{
// Append
return str + value;
}
else
{
// Remove ending part + append
return str.Remove(index) + value;
}
}
}
// abchello worldopqrstuvwxyz
string text = "abcdefghijklmnopqrstuvwxyz".OverwriteWith("hello world", 3);
// abchello world
string text2 = "abcd".OverwriteWith("hello world", 3);
// abchello world
string text3 = "abc".OverwriteWith("hello world", 3);
// hello world
string text4 = "abc".OverwriteWith("hello world", 0);