c#

c#如何替换指定位置字符串

小亿
239
2024-08-01 21:12:11
栏目: 编程语言

在C#中,可以使用Substring()方法和String.Replace()方法来替换指定位置的字符串。

例如,假设我们有一个字符串如下:

string originalString = "Hello, world!";

我们想要将"world"替换为"everyone",可以这样做:

int index = originalString.IndexOf("world"); // 找到要替换的字符串的起始位置
string replacedString = originalString.Substring(0, index) + "everyone" + originalString.Substring(index + "world".Length);

在这个例子中,我们首先使用IndexOf()方法找到要替换的字符串的起始位置,然后使用Substring()方法将原始字符串拆分为替换部分之前和之后的部分,并将替换的字符串连接起来。

另外,如果我们要替换所有的"world",可以使用String.Replace()方法:

string replacedString = originalString.Replace("world", "everyone");

这将在原始字符串中找到所有的"world"并替换为"everyone"。

0
看了该问题的人还看了