Start learning free

LESSON 61 OF 347 · STRINGS I

String Replace in C#: The Replace Method

Lesson Read the full explanation

In Java, you can replace part of a string using the replace() method:

s.Replace(oldValue, newValue)               // replaces all occurrences
new Regex(pattern).Replace(s, newValue, 1)  // replaces first match

Here are some examples:

string sentence = "I love cats";
string result = sentence.Replace("cats", "dogs");
Console.WriteLine(result);  // "I love dogs"

string text = "aaa";
Console.WriteLine(text.Replace("a", "b"));  // "bbb"

replace() returns a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign it to result.

STEP 1 OF 1
    Ctrl + Enter to check

    C# · STRINGS I

    String Replace in C#, explained

    Replacing text

    The Replace method swaps every occurrence of one piece of text for another. It takes the old value and the new value, and it returns a new string:

    string sentence = "I love cats";
    string result = sentence.Replace("cats", "dogs");
    
    Console.WriteLine(result);    // I love dogs
    Console.WriteLine(sentence);  // I love cats
    

    The original is untouched. Strings in C# are immutable, so Replace builds a fresh string and leaves sentence as it was. If you want to keep the change, store the result, either in a new variable or back in the same one with sentence = sentence.Replace(...). Calling sentence.Replace("cats", "dogs"); by itself does nothing useful.

    Every occurrence is replaced

    Replace does not stop at the first match:

    string text = "aaa";
    
    Console.WriteLine(text.Replace("a", "b"));      // bbb
    Console.WriteLine("abc".Replace("x", "y"));     // abc
    

    When nothing matches, you get the same text back. It is not an error.

    Strings and characters

    There is also a version that takes single characters, written with single quotes:

    Console.WriteLine("a-b-c".Replace('-', '+'));  // a+b+c
    

    The old value can't be an empty string. "abc".Replace("", "x") throws an ArgumentException. The new value can be empty, which removes the old text: "a-b-c".Replace("-", "") gives abc.

    Chaining and removing

    Because each call returns a string, you can chain calls. Each one works on the result of the one before it:

    Console.WriteLine("Hello".Replace("l", "L").Replace("H", "J"));  // JeLLo
    Console.WriteLine("a b  c".Replace(" ", ""));                    // abc
    

    Replacing with an empty string is the standard way to delete every copy of some text.

    Ignoring case

    An overload accepts a StringComparison value for matches that ignore case:

    string s = "I love Cats";
    
    Console.WriteLine(s.Replace("cats", "dogs"));                                      // I love Cats
    Console.WriteLine(s.Replace("cats", "dogs", StringComparison.OrdinalIgnoreCase));  // I love dogs
    

    Replacing only the first match

    C# strings have no built-in "replace first" method. Two common ways to do it are shown here, both on "banana". The first finds the position with IndexOf and rebuilds the string:

    string s = "banana";
    int p = s.IndexOf("a");
    
    string result = s.Substring(0, p) + "o" + s.Substring(p + 1);
    Console.WriteLine(result);  // bonana
    

    The second uses a regular expression and its count argument. It needs using System.Text.RegularExpressions; at the top of the file:

    Console.WriteLine(new Regex("a").Replace("banana", "o", 1));  // bonana
    

    The regular expression version treats its pattern as a pattern, not as plain text, so characters such as . or * have special meaning. For plain text the IndexOf approach is safer.

    Cleaning a string in steps

    Because the original never changes, code that cleans a string in several steps keeps reassigning the same variable. This pattern is typical:

    string phone = "555-123-4567";
    
    phone = phone.Replace("-", "");
    phone = phone.Replace("5", "#");
    
    Console.WriteLine(phone);  // ###1234#67
    

    Without the phone = on each line, the second call would still see the dashes. Each assignment hands the next step the cleaned string.

    The search text is matched as plain text and from left to right without overlapping. Replacing "aa" with "b" in "aaa" gives ba, with one replacement and not two, because the second a is already used by the first match.

    A tidy way to think about it is that Replace is a find-and-substitute pass over the whole string. It is a good fit for fixed text such as removing separators, correcting a repeated typo or swapping one word for another. For rules like "any digit" or "the first word", you need a regular expression instead.

    The exercise, step by step

    The lesson gives you sentence set to "I love cats".

    1. Declare a string named result. The method returns a string.
    2. Call sentence.Replace("cats", "dogs") and assign it to result. The old value comes first and the new value second.
            string sentence = "I love cats";
    
            string result = sentence.Replace("cats", "dogs");
    

    Now result holds I love dogs and sentence still holds I love cats.

    Common mistakes

    • Using lowercase replace. C# method names start with a capital letter. replace does not compile.
    • Swapping the arguments. Replace("dogs", "cats") looks for dogs, finds nothing, and returns the original text.
    • Ignoring the returned string. The original does not change, so the result must be stored.
    • Forgetting case. Replace("Cats", "dogs") does not match cats, because the comparison is case-sensitive by default.

    Key takeaways

    • s.Replace(oldValue, newValue) replaces all occurrences and returns a new string.
    • The original string never changes.
    • No match means the same text comes back.
    • Replacing only the first match takes extra work, such as IndexOf with Substring.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free