C# `String.Replace()`: Efficiently Replacing Substrings within Strings
Learn how to use C#'s `String.Replace()` method for efficient substring replacement. This tutorial demonstrates its usage with both character and string replacements, highlighting its ability to perform multiple replacements and its importance in string manipulation tasks.
Replacing Substrings in C# Strings with `String.Replace()`
Understanding `String.Replace()`
The C# `Replace()` method creates a new string by replacing all occurrences of a specified substring within the original string. This is a very common operation used to modify and manipulate string data. It's important to note that the original string remains unchanged; `Replace()` returns a new string with the replacements made.
`String.Replace()` Method Signatures
The `Replace()` method has two versions:
public string Replace(char oldChar, char newChar);
: Replaces all occurrences of a specified character with another character.public string Replace(string oldValue, string newValue);
: Replaces all occurrences of a specified string with another string.
Examples: Using `String.Replace()`
Example 1: Replacing a Character
This example replaces all occurrences of the character 'F' with 'C' in the string "Hello F#".
C# Code
using System;
public class StringReplaceExample {
public static void Main(string[] args) {
string str = "Hello F#";
string newStr = str.Replace('F', 'C');
Console.WriteLine(newStr); // Output: Hello C#
}
}
Example 2: Replacing a Substring
This example replaces all occurrences of the string "Hello" with "Cheers".
C# Code
using System;
public class StringReplaceExample {
public static void Main(string[] args) {
string str = "Hello C#, Hello .Net, Hello World";
string newStr = str.Replace("Hello", "Cheers");
Console.WriteLine(newStr);
//Output: Cheers C#, Cheers .Net, Cheers World
}
}
Conclusion
The `Replace()` method is a fundamental string manipulation function in C#. Its simplicity and efficiency make it a valuable tool for various text processing tasks. Remember that `Replace()` creates a new string; the original string remains unchanged.