.Replace()
The .Replace()
method returns a new string where every instance of a certain character or substring in the original string is swapped with a different specified character or substring.
Syntax
// Replaces old character with new character.
myString.Replace(char oldChar, char newChar);
// Replaces old string with new string.
myString.Replace(string oldString, string newString);
The .Replace()
method takes the original string returns a new string with the following changes in it:
- All occurrences of indicated character are replaced with another one.
- All occurrences of indicated string are replaced with another one.
Note: If
oldChar
oroldString
is not found in the original string, than the method returns the string without changes.
Note: If
newChar
ornewString
isnull
, than all occurrences ofoldChar
oroldString
are removed.
Note: The
.Replace()
method does not modify the originalstring
, it always produces a new string.
Example 1
The following example takes the string
named oldString
, replaces all the hyphen characters -
with comma characters ,
, and returns the new string
named newString
.
using System;public class Example{public static void Main(string[] args){string oldString = "A-B-C-D-E-F-G-H-I";string newString = oldString.Replace('-', ',');Console.WriteLine($"Old string: \"{oldString}\"");Console.WriteLine($"New string: \"{newString}\"");}}
It produces the following output to the console:
Old string: "A-B-C-D-E-F-G-H-I"New string: "A,B,C,D,E,F,G,H,I"
Example 2
The following example takes the string
named wrongString
, replaces the word fourth
with the word third
, and returns the new string
named rightString
.
using System;public class Example{public static void Main(string[] args){string wrongString = "Earth is the fourth planet from the Sun.";string rightString = wrongString.Replace("fourth", "third");Console.WriteLine($"False statement: {wrongString}");Console.WriteLine($"True statement: {rightString}");}}
It produces the following output to the console:
False statement: Earth is the fourth planet from the Sun.True statement: Earth is the third planet from the Sun.
Codebyte Example
In the following runnable example, the .Replace()
method is used to create a replacedString
from the originalString
. Then both strings are printed to the console:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours