![]() |
VOOZH | about |
In C#, the Replace() method is used to replace all occurrences of a specified substring or character in a string with another substring or character. This method is particularly useful for string manipulation tasks, such as formatting or cleaning up data.
Example : Using Replace() method to replace "World" with "Geeks" in a string.
Before Replacing: Hello, World After Replacing: Hello, Geeks
Explanation: In the above example, we use a Replace() method of the String class to replace the World with Geeks.
public string Replace(char oldChar, char newChar)
public string Replace(string oldValue, string newValue)
Parameters:
Return Type:
Exceptions:
Example 1: Using the Replace() method to replace all occurrences of a specified substring with a new substring.
Hello, Geeks
Explanation: In the above example, the Replace() method replaces "Geek" with "Geeks" in the original string and returns a new string.
Example 2: Using the Replace() method to replace the specified character from the string.
Modified String: Hella, Warld!
Explanation: In the above example, we use the Replace() method which replaces all occurrences of a specified character with a new character. As shown the character 'o' replaces with 'a'.
Example 3: Using the Replace() method in a Case-Sensitive Manner.
Hello, World!
Explanation: In the above example, the string value passed as "hello" (lowercase) is not found in the original string, so no replacement was done because the Replace() method is case-sensitive.
Example 4: Performing multiple replacement operations on the String (Replacement’s Chain) using the Replace() method.
Modified String: Hello, Geeks! Welcome to the Geeks of C Sharp!
Explanation: In the above example, the multiple replacement operation is performed using the Replace() method of string class the world "World" with "Geeks" and "C#" with "C Sharp" using method chaining.