0
0
CsharpHow-ToBeginner · 3 min read

How to Replace Text in a String in C# Easily

In C#, you can replace text in a string using the Replace method, which returns a new string with specified characters or substrings replaced. Use string.Replace(oldValue, newValue) to replace all occurrences of oldValue with newValue.
📐

Syntax

The Replace method in C# is used to create a new string by replacing all occurrences of a specified substring or character with another substring or character.

  • oldValue: The substring or character you want to replace.
  • newValue: The substring or character you want to use as a replacement.
  • The method returns a new string; the original string remains unchanged because strings are immutable in C#.
csharp
string newString = originalString.Replace(oldValue, newValue);
💻

Example

This example shows how to replace all occurrences of the word "cat" with "dog" in a sentence.

csharp
using System;

class Program
{
    static void Main()
    {
        string original = "The cat sat on the cat mat.";
        string replaced = original.Replace("cat", "dog");
        Console.WriteLine(replaced);
    }
}
Output
The dog sat on the dog mat.
⚠️

Common Pitfalls

Strings are immutable: The Replace method does not change the original string but returns a new one. You must assign the result to a variable.

Case sensitivity: The Replace method is case-sensitive. To replace text regardless of case, you need extra steps like using Regex with case-insensitive options.

Null or empty values: Passing null as oldValue throws an exception. Passing an empty string as oldValue will throw an ArgumentException.

csharp
/* Wrong way: This does not change original string */
string text = "Hello World";
text.Replace("World", "C#");
Console.WriteLine(text); // Output: Hello World

/* Right way: Assign the result */
text = text.Replace("World", "C#");
Console.WriteLine(text); // Output: Hello C#
Output
Hello World Hello C#
📊

Quick Reference

MethodDescriptionExample
Replace(string oldValue, string newValue)Replaces all occurrences of a substring."hello".Replace("l", "r") → "herro"
Replace(char oldChar, char newChar)Replaces all occurrences of a character."hello".Replace('e', 'a') → "hallo"

Key Takeaways

Use string.Replace(oldValue, newValue) to replace text in C# strings.
Strings are immutable; always assign the result of Replace to a variable.
Replace is case-sensitive; use Regex for case-insensitive replacements.
Passing null or empty strings as oldValue causes exceptions.
Replace works for both substrings and single characters.