0

如何用字符串替换字符串中的字符?

例如:用“test”替换所有字符的“e”:“Hello World”->“Htestllo World”。

A,string.replace(char,string),如果你愿意的话。

4

3 回答 3

6

您可以使用 Replace 方法的字符串版本:

"Hello World".Replace("e", "a long string");
于 2012-09-23T20:15:03.407 回答
2
// let's pretend this was a char that came to us from somewhere, already as a char...
char c = char.Parse("e");

// Here is the string we want to change...
string str1 = "Hello World."

// now we'll have to convert the char we have, to a string to perform the replace...
string charStr = c.ToString();

// now we can do the replace...
string str2 = str1.Replace(charStr,"test");
于 2012-09-23T20:35:24.443 回答
1

您可以使用String.Replace将字符串中出现的任何字符串替换为另一个字符串。

返回一个新字符串,其中当前实例中出现的所有指定字符串都替换为另一个指定字符串。

示例用法:

string original = "Hello world";
string changed = original.Replace("e", "t");
Console.WriteLine(changed); // "Htllo world"
于 2012-09-23T20:18:30.777 回答