Start learning free

LESSON 62 OF 674 · STRINGS I

String Replace in C#

Lesson

In C#, 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