.Replace()

Published Mar 26, 2023Updated Jun 1, 2023
Contribute to Docs

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 or oldString is not found in the original string, than the method returns the string without changes.

Note: If newChar or newString is null, than all occurrences of oldChar or oldString are removed.

Note: The .Replace() method does not modify the original string, 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:

Code
Output
Loading...

All contributors

Looking to contribute?

Learn C# on Codecademy