首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何通过位置替换字符串的一部分?

如何通过位置替换字符串的一部分?
EN

Stack Overflow用户
提问于 2011-02-16 19:02:20
回答 20查看 287.3K关注 0票数 180

我有这个字符串:ABCDEFGHIJ

我需要用字符串ZX替换从位置4到位置5

它看起来像这样:ABCZXFGHIJ

但不能用于string.replace("DE","ZX") -我需要使用position

我该怎么做呢?

EN

回答 20

Stack Overflow用户

回答已采纳

发布于 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代码更具可读性。

票数 216
EN

Stack Overflow用户

发布于 2011-02-16 19:24:51

string s = "ABCDEFGH";
s= s.Remove(3, 2).Insert(3, "ZX");
票数 234
EN

Stack Overflow用户

发布于 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类不需要初始化,而且它使用了更基本的操作。如果我错了,请纠正我。:)

票数 48
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5015593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档