【发布时间】:2013-08-22 03:29:30
【问题描述】:
如何覆盖字符串?示例:
string text = "abcdefghijklmnopqrstuvwxyz".OverwriteWith("hello world", 3);
// text == "abchello worldopqrstuvwxyz"
当然没有这种方法。但是
- .NET Framework 中有内置的东西吗?
- 如果没有,我怎样才能有效地将一个字符串写入另一个字符串?
【问题讨论】:
如何覆盖字符串?示例:
string text = "abcdefghijklmnopqrstuvwxyz".OverwriteWith("hello world", 3);
// text == "abchello worldopqrstuvwxyz"
当然没有这种方法。但是
【问题讨论】:
您只需要使用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 中的字符串是 immutable types。您无法更改它们。即使你认为你改变了它们,你实际上也创建了一个新的字符串对象。
如果您想使用可变字符串,请查看 StringBuilder 类。
这个类表示一个类字符串对象,其值是可变的 字符序列。该值被认为是可变的,因为它可以 在创建后通过追加、删除、 替换或插入字符。
【讨论】:
immutable 的术语?好主意……
你想要的是一个扩展方法:
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);
【讨论】:
你可以试试这个解决方案,这可能会对你有所帮助..
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();
参考:Click Here!!
【讨论】:
简短的回答,你不能。字符串是不可变的类型。这意味着它们一旦被创建,就不能被修改。
如果你想在内存中操作字符串,c++方式,你应该使用StringBuilder。
【讨论】: