C# String Replace() Method

http‮/:s‬/www.theitroad.com

The Replace() method in C# is used to replace all occurrences of a specified substring in a string with another substring. The resulting string contains the new substring in place of the old substring.

The syntax of the Replace() method is as follows:

string.Replace(oldValue, newValue);

Here, oldValue is the substring to be replaced, and newValue is the substring to replace it with.

For example, to replace all occurrences of the substring "World" in a string with the substring "Universe", you can use the following code:

string text = "Hello World";
string newText = text.Replace("World", "Universe");
Console.WriteLine(newText);  // Output: "Hello Universe"

In this example, the Replace() method is used to replace all occurrences of the substring "World" in the string "Hello World" with the substring "Universe". The resulting string "Hello Universe" is then assigned to the newText variable and printed to the console using the WriteLine() method.

You can also use the Replace() method to remove a substring from a string. For example, to remove all occurrences of the substring "o" from a string, you can use the following code:

string text = "Hello World";
string newText = text.Replace("o", "");
Console.WriteLine(newText);  // Output: "Hell Wrld"

In this example, the Replace() method is used to replace all occurrences of the substring "o" in the string "Hello World" with an empty string (""). The resulting string "Hell Wrld" is then assigned to the newText variable and printed to the console.