C# Tutorial C# Advanced C# References

C# String - Replace() Method



The C# Replace() method returns the string with the specified character/string replaced with new character/string of the given string.

Syntax

public string Replace (string oldValue, string newValue, 
              StringComparison comparisonType);
public string Replace (string oldValue, string newValue);
public string Replace (char oldValue, char newValue);
public string Replace (string oldValue, string newValue, 
              bool ignoreCase, System.Globalization.CultureInfo culture);

Parameters

oldValue Specify the character or string to be replaced.
newValue Specify the character or string to replace all occurrences of oldValue.
ignoreCase true to ignore casing, false otherwise
culture Specify the culture to use when comparing.

Return Value

Returns the replaced version of the string.

Exception

  • Throws ArgumentNullException, if the oldValue is null.
  • Throws ArgumentException, if the oldValue is empty.

Example: Replace character in a string

In the example below, Replace() method returns the string where the whitespaces are replaced by comma , in the string called MyStr.

using System;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = "Red Blue Green Blue";
    string NewStr = MyStr.Replace(" ", ",");

    Console.WriteLine(NewStr); 
  }
}

The output of the above code will be:

Red,Blue,Green,Blue

Example: Replace string in a string

In the example below, Replace() method returns the string where the text World is replaced with new text C# in the given string. The example also describes how to use English-United States and Turkish-Turkey cultures with replace method.

using System;
using System.Globalization;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = "Hello World";

    string NewStr1 = MyStr.Replace("World", "C#");
    Console.WriteLine(NewStr1); 

    string NewStr2 = MyStr.Replace("wORLd", "CSharp", true, new CultureInfo("en-US"));
    Console.WriteLine(NewStr2); 
  }
}

The output of the above code will be:

Hello C#

Hello CSharp

❮ C# String Methods