我有这个字符串:ABCDEFGHIJ
我需要用字符串ZX
替换从位置4到位置5
它看起来像这样:ABCZXFGHIJ
但不能用于string.replace("DE","ZX")
-我需要使用position
我该怎么做呢?
发布于 2011-02-16 19:06:15
在字符串中添加和删除范围的最简单方法是使用StringBuilder
。
var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "ZX");
theString = aStringBuilder.ToString();
另一种选择是使用String.Substring
,但我认为StringBuilder
代码更具可读性。
发布于 2011-02-16 19:24:51
string s = "ABCDEFGH";
s= s.Remove(3, 2).Insert(3, "ZX");
发布于 2014-03-20 04:59:42
ReplaceAt(整型索引,整型长度,字符串替换)
下面是一个不使用StringBuilder或子字符串的扩展方法。此方法还允许替换字符串超出源字符串的长度。
//// str - the source string
//// index- the start location to replace at (0-based)
//// length - the number of characters to be removed before inserting
//// replace - the string that is replacing characters
public static string ReplaceAt(this string str, int index, int length, string replace)
{
return str.Remove(index, Math.Min(length, str.Length - index))
.Insert(index, replace);
}
使用此函数时,如果希望整个替换字符串替换尽可能多的字符,则将长度设置为替换字符串的长度:
"0123456789".ReplaceAt(7, 5, "Hello") = "0123456Hello"
否则,您可以指定要删除的字符数:
"0123456789".ReplaceAt(2, 2, "Hello") = "01Hello456789"
如果将长度指定为0,则此函数的作用与insert函数相同:
"0123456789".ReplaceAt(4, 0, "Hello") = "0123Hello456789"
我猜这会更有效,因为StringBuilder类不需要初始化,而且它使用了更基本的操作。如果我错了,请纠正我。:)
https://stackoverflow.com/questions/5015593
复制相似问题