How to replace strings using C#?

In C#, you can use the string.Replace() method to substitute one string for another. This method takes two parameters: the first is the string to be replaced and the second is the new string to replace it with.

Here is an example code:

string originalString = "Hello, World!";
string replacedString = originalString.Replace("World", "C#");

Console.WriteLine(replacedString); // 输出:Hello, C#!

In the code above, we replaced “World” with “C#” in the original string and stored the result in the replacedString variable. Then, we used the Console.WriteLine() method to output the replaced string to the console.

Please note that the Replace() method is case-sensitive. To perform a case-insensitive replacement, you can use an overloaded version of the String.Replace() method and specify StringComparison.OrdinalIgnoreCase as the third parameter. For example:

string originalString = "Hello, world!";
string replacedString = originalString.Replace("WORLD", "C#", StringComparison.OrdinalIgnoreCase);

Console.WriteLine(replacedString); // 输出:Hello, C#!

In the examples above, “WORLD” in the original string will be replaced with “C#” regardless of whether it is in uppercase or lowercase.

bannerAds