C# Replace

Replace

Replace changes string data. It changes all occurrences of one substring into another substring. It also handles character replacements. The C# string type offers Replace. The StringBuilder type also offers a replace method.

StringBuilder

Note:It is possible to replace strings in an optimized way.
We test and benchmark Replace.

Example

String type

To start we see a simple example of using the string Replace method. Please note that you must assign the result of the string Replace method to a new variable. Other Replace methods in the base class library may not require this.

Program that uses Replace: C#

using System;

class Program
{
    static void Main()
    {
	const string s = "Darth Vader is scary.";
	Console.WriteLine(s);

	// Note:
	// You must assign the result of Replace to a new string.
	string v = s.Replace("scary", "not scary");
	Console.WriteLine(v);
    }
}

Output

Darth Vader is scary.
Darth Vader is not scary.

Every instance

The Replace methods replace every instance of the specified substring. To demonstrate, the next console program replaces the word "Net" with the word "Basket". Don't call Replace two times in the example.

Note:The second Replace will not do anything and will result in needless CPU cycles being used.

Program 2: C#

using System;

class Program
{
    static void Main()
    {
	const string s = "Dot Net Perls is about Dot Net.";
	Console.WriteLine(s);

	// Note:
	// You must assign the result to a new variable.
	// Every instance is replaced.
	string v = s.Replace("Net", "Basket");
	Console.WriteLine(v);
    }
}

Output

Dot Net Perls is about Dot Net.
Dot Basket Perls is about Dot Basket.

StringBuilder

To continue, we see the basics of StringBuilder and its Replace and Insert methods. With StringBuilder, Replace works the same way as with strings but it doesn't need its result to be assigned.

Program that uses StringBuilder: C#

using System;
using System.Text;

class Program
{
    static void Main()
    {
	const string s = "This is an example.";

	// A
	// Create new StringBuilder from string
	StringBuilder b = new StringBuilder(s);
	Console.WriteLine(b);

	// B
	// Replace the first word
	// The result doesn't need assignment
	b.Replace("This", "Here");
	Console.WriteLine(b);

	// C
	// Insert the string at the beginning
	b.Insert(0, "Sentence: ");
	Console.WriteLine(b);
    }
}

Output

This is an example.
Here is an example.
Sentence: Here is an example.
Letters of the alphabet: ABC

In this example, we create a StringBuilder. In part A, we use the constructor to initialize the StringBuilder with a short sentence. Next we print the StringBuilder to the console with Console.WriteLine.

Console.WriteLine

In part B, it replaces the word "This" with the word "Here". The result has the new word in place of the old word.
In part C,
we see a similar method,
the Insert method. It is like Replace where an empty string is replaced.

Insert

Problem

This section provides information

The biggest problem with Replace is that it creates more string copies each time it is called. This can often lead to measurable performance problems in large projects. Microsoft notes that Replace returns a new string.

This method does not modify the value of the current instance. Instead, it returns a new string in which all occurrences of oldValue are replaced by newValue.

String.Replace Method: MSDN

Rewrite with StringBuilder

Fortunately, it is usually easy to rewrite your wasteful string Replace code with StringBuilder Replace. For the example, I show the original code that uses string and then the new StringBuilder code.

String Replace example: C#

/// <summary>
/// A - Eliminates extra whitespace.
/// </summary>
static string MinifyA(string p)
{
    p = p.Replace("  ", string.Empty);
    p = p.Replace(Environment.NewLine, string.Empty);
    p = p.Replace("\\t", string.Empty);
    p = p.Replace(" {", "{");
    p = p.Replace(" :", ":");
    p = p.Replace(": ", ":");
    p = p.Replace(", ", ",");
    p = p.Replace("; ", ";");
    p = p.Replace(";}", "}");
    return p;
}

StringBuilder Replace example: C#

/// <summary>
/// B - Eliminates extra whitespace.
/// </summary>
static string MinifyB(string p)
{
    StringBuilder b = new StringBuilder(p);
    b.Replace("  ", string.Empty);
    b.Replace(Environment.NewLine, string.Empty);
    b.Replace("\\t", string.Empty);
    b.Replace(" {", "{");
    b.Replace(" :", ":");
    b.Replace(": ", ":");
    b.Replace(", ", ",");
    b.Replace("; ", ";");
    b.Replace(";}", "}");
    return b.ToString();
}

MinifyA ends up creating lots of string copies. It uses string constants such as Environment.NewLine and string.Empty. It replaces whitespace around punctuation. It can be used to strip whitespace from CSS files.

Environment.NewLinestring.Empty

MinifyB is similar but uses StringBuilder. It instantiates a new StringBuilder from the parameter string. It does the same replacements as Method A. The return value of Replace doesn't need to be assigned.

Performance optimization

Benchmark. We next see if there is a difference between Method A, which uses string Replace, and Method B, which uses StringBuilder Replace. It is great to know the two are different. But is the timing difference significant?

Replace methods benchmark for short strings
    20 characters in strings, 10000 iterations.

Method A - String Replace:         5.60 seconds
Method B - StringBuilder Replace:  0.62 seconds [faster]

Replace methods benchmark for long strings
    1000 characters in strings, 10000 iterations.

Method A - String Replace:        21.80 seconds
Method B - StringBuilder Replace   4.89 seconds [faster]
Squares

I found that string Replace took considerably more time in this case. This is because of the repeated string copying due to the semantics of string Replace, versus StringBuilder which modifies buffers in-place.

Thus:Avoiding string Replace in situations where more than one replacement is required is a good guideline.

And:There may be cases where string Replace can perform better, even on more than one Replace.

Note:The cost of the StringBuilder constructor in some cases makes MinifyB slower. This occurs on lengthy input strings.

Programming tip

Also, some forms of the Replace method are faster than others. For example, using char arguments is faster than string arguments. The Replace method is faster if no changes are made to the underlying string.

Replace Performance

Split

Split strings

You can use Replace on a string you want to split to filter out escaped characters that would otherwise cause incorrect results. You can do this by replacing the characters before calling Split, and then restoring them.

Split

Whitespace

We often need to remove or change whitespace in strings, particularly those read in from files. There is a complete guide to replacing or converting whitespace—such as tabs, spaces, and line breaks.

Whitespace

Summary

C# programming language

We viewed some interesting Replace examples. And we learned about the behavior of two Replace methods, as well as Insert. String Replace is different from StringBuilder Replace. But on the surface they are the same.

Tip:StringBuilder is purely an optimization, but considering the prevalence of string usage, it is critical.


C#: String