Hit enter after type your search item

What is C# String Replace method?

The string replace method is used to return a new string after changing all occurrences of the given substring in the source string.

In C#, the string is immutable i.e. once created it cannot be changed. So, the original string remains the same after using the string replace method.

A simple example of the Replace method for this source string can be:

“This is C# tutorial”

string str_new = source_str.Replace(“C#”, “C Sharp”);

I will show you complete examples with variations for C# Replace method, first have a look at the syntax of using it.

Syntax of using Replace method

public string Replace (string oldValue, string newValue);

An example of String Replace method

In this example, we have a source string that is declared and assigned a value. This is followed by using the Replace method where we will replace the word “C#” to “C Sharp” for the demo only:


The output of this code:

c# string replace

What if multiple occurrences exist in the source string?

As mentioned earlier, the C# Replace method will change all the occurrences of the existing substring by the given substring.

To demonstrate that, I have used the word “C#” twice in the source string. Then, I used the Replace method for replacing “C#” by “C Sharp”. Have a look at what we got as the output:


The output:

c# string replace all

Is Replace method case sensitive?

The Replace method is case sensitive. That means “C#” and “c#” are taken differently if provided as the New_string in the Replace method.

To demonstrate that, I used the same words in the source string with different cases:


The output:

c# string replace case sensitive

You can see in the output graphic, only the first occurrence of “C#” is replace by “C Sharp” whereas the second occurrence remains the same i.e. “c#”.

How to limit the number of replacements?

In certain scenarios, you may require changing only the first one or two or so occurrences of the existing term by new term rather than replacing all.

Unfortunately, there is no straight-forward method of limiting the number of replacements for the old_value to new_value in the soruce string as using the Replace method.

However, you may use different ways of limiting the replacements. One of the ways is using the Regex.Replace method for limiting the number of replacements.

The code:


The output:

c# string replace limit

You can see, the source string contains three occurrences of the word “C#”. By using the regex Replace method, we specified “1” as the third argument for limiting the number of replacements.

It started from left and only changed the first occurrence of “C#” to “C Sharp”.

Learn more about regex replace method here.

This div height required for enabling the sticky sidebar