How is the usage of replace in C#?
In C#, Replace is a string method used to replace all occurrences in a string.
The basic usage of “Replace” is as follows:
string replacedString = originalString.Replace(oldValue, newValue);
- The originalString is the initial string that needs to be replaced.
- oldValue is the substring to be replaced.
- “newValue is the new string used for replacement.”
The Replace method will return a new string where all occurrences of oldValue are replaced with newValue. If there are no occurrences of oldValue in the original string, it will return the original string.
Here is a simple example:
string originalString = "Hello World!";
string replacedString = originalString.Replace("World", "C#");
Console.WriteLine(replacedString);
// 输出:Hello C#!
In the example above, the string “World” in the original string is replaced with “C#” and assigned to replacedString. The final output is “Hello C#!”.
It is important to note that the Replace method is case-sensitive. If you want to make a case-insensitive replacement, you can use the StringComparison enumeration as the third parameter.
string originalString = "Hello world!";
string replacedString = originalString.Replace("WORLD", "C#", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(replacedString);
// 输出:Hello C#!
In the example above, the StringComparison.OrdinalIgnoreCase parameter indicates that the replacement is case-insensitive. Even if the “world” in the original string is lowercase, it will be replaced with “C#”.