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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
