C#
Replace
Learn to replace text inside a string with Replace.
Replacing with Replace
The Replace method swaps every match of a substring with another substring. It takes two arguments: the old value and the new value. It does not mutate the original; it returns a new string.
For example, "buy pen".Replace("pen", "book") returns "buy book". All matches are replaced, not just the first. To keep the change, assign the result to a variable.
Chaining Replace calls
When you need several replacements, you can chain Replace calls one after another. Since each call returns a string, you can pass the result straight into the next call.
For example, text.Replace("a", "A").Replace("b", "B") first swaps every 'a', then every 'b'. This lets you do a multi-step cleanup in a single line.
Char and string parameters
Replace works in two forms: Replace(char, char) swaps a single character, while Replace(string, string) swaps longer substrings. You pick the right one for the job.
For example, "1-2-3".Replace('-', '/') gives "1/2/3", while "1-2-3".Replace("-", " - ") gives "1 - 2 - 3". Both are valid; you choose based on the data you have.
Exercise Replace two words
Assign "Black car drives fast" to text. Then use a chained text.Replace(...).Replace(...) to make two changes: "Black" → "Red" and "fast" → "slow". Assign the result to result and print it with Console.WriteLine.
Show example solution
First assign text, then result = text.Replace("Black", "Red").Replace("fast", "slow"); and add Console.WriteLine(result);
Example solution:
using System;
class Program
{
static void Main()
{
string text = "Black car drives fast";
string result = text.Replace("Black", "Red").Replace("fast", "slow");
Console.WriteLine(result);
}
}
Test yourself
-
Does Replace mutate the original string?
string s = "a-b-a";
string r = s.Replace("a", "x");
- Yes, s becomes "x-b-x"
- No, s stays "a-b-a", r is "x-b-x"
- Only the first "a" is replaced
- Replace throws an error
Show answer
No, s stays "a-b-a", r is "x-b-x" — Correct! Strings are immutable; Replace returns a new string.
-
Replace the word
string text = "cat bird cat";
string result = text____;
Console.WriteLine(result);
Show answer
string text = "cat bird cat";
string result = text.Replace("cat", "dog");
Console.WriteLine(result);
-
How to replace two words in one line?
string s = "black car";
- s.Replace("black", "red").Replace("car", "truck")
- s.Replace("black", "car", "red", "truck")
- s.Replace(["black","car"], ["red","truck"])
- s.Replace("black", "red"); s.Replace("car", "truck");
Show answer
s.Replace("black", "red"); s.Replace("car", "truck"); — Correct! Chained Replace applies both changes in one line.
Next lesson: Summary - Advanced strings