C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In C#, you can replace characters or substrings within a string using the Replace
method of the System.String
class. In this tutorial, we'll cover the basics of using the Replace
method effectively.
The Replace
method has two overloaded versions:
public string Replace(char oldValue, char newValue) public string Replace(string oldValue, string newValue)
oldValue
: The character or substring to be replaced.newValue
: The character or substring to replace the oldValue
.The method returns a new string with all occurrences of oldValue
replaced with newValue
.
Examples:
string original = "The quick brown fox jumps over the lazy dog."; string replaced1 = original.Replace('o', 'O'); // "The quick brOwn fOx jumps Over the lazy dOg." string replaced2 = original.Replace("fox", "cat"); // "The quick brown cat jumps over the lazy dog."
Note that strings in C# are immutable, which means that the Replace
method does not modify the original string. Instead, it creates a new string with the desired content.
The Replace
method throws an ArgumentException
if the oldValue
is an empty string or null. To avoid this exception, you can validate the input before calling the Replace
method:
string original = "The quick brown fox jumps over the lazy dog."; string oldValue = "fox"; string newValue = "cat"; if (!string.IsNullOrEmpty(oldValue)) { string replaced = original.Replace(oldValue, newValue); // "The quick brown cat jumps over the lazy dog." } else { // Handle invalid input }
In this tutorial, we covered how to replace characters or substrings within a string using the Replace
method in C#. Remember that strings are immutable, so the Replace
method returns a new string with the specified content. Be sure to handle potential ArgumentException
cases by validating the input before calling the method.
How to use Replace in C#
The Replace
method in C# is used to replace occurrences of a specified substring or characters within a string.
string originalString = "Hello, World!"; string modifiedString = originalString.Replace("World", "C#"); // Result: "Hello, C#!"
String replacement techniques in C#
String replacement in C# involves replacing specific characters or substrings within a given string.
string input = "C# is awesome!"; string output = input.Replace("awesome", "amazing"); // Result: "C# is amazing!"
C# Replace method for character substitution
Use Replace
to substitute individual characters in a string.
string phrase = "C# is fun!"; string updatedPhrase = phrase.Replace('f', 'F'); // Result: "C# is Fun!"
Replacing substrings in a string with Replace in C#
Replace substrings within a string using the Replace
method.
string text = "C# programming is interesting."; string modifiedText = text.Replace("interesting", "exciting"); // Result: "C# programming is exciting."
Case-insensitive string replacement in C#
Perform case-insensitive string replacement by using StringComparison
option.
string sentence = "C# is case sensitive!"; string updatedSentence = sentence.Replace("c#", "C#", StringComparison.OrdinalIgnoreCase); // Result: "C# is C# sensitive!"
Replacing multiple occurrences with Replace in C#
Replace multiple occurrences of a substring within a string.
string repeatedText = "C# C# C#"; string updatedText = repeatedText.Replace("C#", "CSharp"); // Result: "CSharp CSharp CSharp"
Replacing with an empty string using Replace in C#
Use Replace
with an empty string to remove specified characters or substrings.
string stringWithSpaces = "Remove spaces from this string."; string stringWithoutSpaces = stringWithSpaces.Replace(" ", ""); // Result: "Removespacesfromthisstring."
Wildcard and pattern-based replacement in C#
Employ wildcard patterns for advanced string replacement scenarios.
string data = "C# is powerful!"; string updatedData = Regex.Replace(data, @"\bpow(er|)\b", "amazing"); // Result: "C# is amazing!"
Using StringBuilder for efficient string replacement in C#
For multiple replacements, use StringBuilder
for better performance.
StringBuilder builder = new StringBuilder("C# is great!"); builder.Replace("C#", "CSharp").Replace("great", "awesome"); string result = builder.ToString(); // Result: "CSharp is awesome!"
Replacing special characters with escape sequences in C#
Replace special characters using escape sequences.
string inputText = "Escape \"this\""; string escapedText = inputText.Replace("\"", "\\\""); // Result: "Escape \"this\""
Handling null or empty strings with Replace in C#
Check for null or empty strings before performing replacements.
string inputString = null; string result = inputString?.Replace("old", "new") ?? "Default"; // Result: "Default"
String replacement and globalization in C#
Consider globalization issues when replacing strings in multi-language scenarios.
string localizedText = "Colour in British English."; string updatedText = localizedText.Replace("Colour", "Color", StringComparison.OrdinalIgnoreCase); // Result: "Color in British English."