C# String Replace

Summary: in this tutorial, you will learn how to use the C# String Replace() method to replace all occurrences of a specified substring in a string with a new substring.

Introduction to the C# String Replace() method

The String Replace() method allows you to replace all occurrences of a substring in a string with a new substring. The Replace() method has several overloads that allow you to customize the replacement operations.

Here’s the basics syntax of the Replace() method:

public string Replace(
   string oldValue, 
   string newValue
)Code language: C# (cs)

The Replace() method takes two parameters:

  • oldValue represents the substring to be replaced.
  • newValue represents the replacement substring.

The Replace() method returns a new string with all occurrences of the oldValue replaced by the newValue.

The following example shows how to use the Replace() method to replace the substring "hi" with the new substring "bye" in the string "hi hi hi":

using static System.Console;

var message = "hi hi hi";
var newMessage = message.Replace("hi", "bye");

WriteLine(newMessage);Code language: C# (cs)

Output:

bye bye byeCode language: C# (cs)

Note that the Replace() does not modify the original string, it returns a new string with the substring oldValue replaced by the new substring newValue.

By default, the Replace() method matches the string case-sensitively. To specify a rule for matching the string before replacement, you can use the following overload of the Replace() method:

public string Replace (
    string oldValue, 
    string? newValue, 
    StringComparison comparisonType
);Code language: C# (cs)

In this method, the comparisonType accepts one of the members of the StringComparison enum that specifies the rule that the method uses to match the oldValue string.

For example, the following program uses the Replace() method that uses the ordinal ignore case rule for replacing the substring "Hi" with the new substring "Bye" in the string "Hi hi hi":

using static System.Console;

var message = "Hi hi hi";
var newMessage = message.Replace(
    "Hi", 
    "Bye", 
    StringComparison.OrdinalIgnoreCase
);

WriteLine(newMessage);Code language: C# (cs)

Output:

Bye Bye ByeCode language: C# (cs)

Summary

  • Use the C# String Replace() method to replace a substring in a string with a new substring.
Was this tutorial helpful ?