Home

Search

C# Replace String Examples

Exchange all instances of one substring with another using Replace. Get the modified string.

dot net perls

Replace. A city can be changed. One building can be added and another destroyed. Think of this city as a string. We remove some characters and add new ones.

Method details. With Replace we search for (and exchange) one pattern for another. What was before is no longer. A change occurs and a new string is returned.

First program. Here we call the Replace method. It is important that we assign Replace's result to a variable. It does not modify the string in-place.
Step 1: We declare and assign the string variable "input" which contains the first letters of the alphabet.
Step 2: We invoke Replace, changing the "abc" to the 2-letter string "hi," and then print the result.
Tip: There are 2 arguments to Replace(): the first is the part we want to change, and the second is the replacement string.
C# program that uses string Replace method using System; class Program { static void Main() { // Step 1: declare and print string. string input = "abcdef"; Console.WriteLine(input); // Step 2: replace part with new string. // ... Assign to the Replace method's result. string output = input.Replace("abc", "hi"); Console.WriteLine(output); } } Output abcdef hidef

Every instance. The Replace method changes every instance of the specified substring. This can sometimes result in unexpected behavior—we must be careful.
Here: The console program replaces the substring "bc" with a 1-char question mark string.
Note: There is no need to call Replace() 2 times. A second Replace() would not do anything.
C# program that causes multiple replacements using System; class Program { static void Main() { const string value = "abcabc"; Console.WriteLine("BEFORE: " + value); // Store the result of Replace() in a variable. // ... All instances of the substring are replaced. string modified = value.Replace("bc", "?"); Console.WriteLine("AFTER: " + modified); } } Output BEFORE: abcabc AFTER: a?a?

Replace, StringBuilder. With StringBuilder, Replace works the same way as with strings, but we do not need to assign the result to anything.
Step 1: To start, we create a StringBuilder. We use the constructor to initialize the StringBuilder with a short string.
StringBuilder
Step 2: We replace the part "abc" with a 1-character string "z." No string copies occur at this step.
Step 3: We use Insert to place a new string part at the start of the StringBuilder.
C# program that uses StringBuilder, Replace method using System; using System.Text; class Program { static void Main() { const string value = "abcdef"; // Step 1: create new StringBuilder from string. StringBuilder builder = new StringBuilder(value); Console.WriteLine(builder); // Step 2: replace the first part. // ... The result doesn't need assignment. builder.Replace("abc", "z"); Console.WriteLine(builder); // Step 3: insert the string at the beginning. builder.Insert(0, "y:"); Console.WriteLine(builder); } } Output abcdef zdef y:zdef

Regex.Replace. The string.Replace() method is limited in the kinds of substrings it can match. With Regex we can match met a-characters like "digit" or "non-word."Regex.Replace
Here: We replace all strings starting with the word "bird" and ending with a digit char and a non-word char (like a space).
Tip: A custom string parsing method could be written, and the result would likely be faster than Regex.Replace—but it would be more work.
C# program that uses Regex.Replace using System; using System.Text.RegularExpressions; class Program { static void Main() { string value = "bird0 cat1 bird2 cat2 bird."; Console.WriteLine("BEFORE: " + value); // Match all strings starting with "bird" and ending with a digit and non-word character. // ... Replace them with an empty string literal. string result = Regex.Replace(value, @"bird\d\W", ""); Console.WriteLine("AFTER: " + result); } } Output BEFORE: bird0 cat1 bird2 cat2 bird. AFTER: cat1 cat2 bird.

Zero-length error. Most parameters (including null) will not cause an exception in Replace(). But if we try to replace an empty string, an ArgumentException is encountered.
Note: It makes no sense to replace an empty string—would the result (in some cases) be an infinitely long string?
ArgumentException
C# program that causes empty string error class Program { static void Main() { string test = "test"; // Cannot replace an empty string. string result = test.Replace("", ""); } } Output Unhandled Exception: System.ArgumentException: String cannot be of zero length. Parameter name: oldValue at System.String.ReplaceInternal(String oldValue, String newValue) at System.String.Replace(String oldValue, String newValue) at Program.Main() in ...

NullReferenceException. As with other string methods, we cannot call Replace on a null instance. If the source string may be null, we must wrap it in an if-check.
Tip: Consider IsNullOrEmpty to test for empty or null strings—an empty string will not need replacements.
IsNullOrEmpty, IsNullOrWhiteSpace
C# program that shows NullReferenceException class Program { static void Main() { string value = null; value.Replace("bird", "?"); } } Output Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main() in ...

Benchmark, StringBuilder. Sometimes StringBuilder can lead to performance improvements. The string type in C# can be faster in many situations.
Version 1: Here we call Replace on a string 3 times. We change all the animal names in the text string.
Version 2: We create a StringBuilder and then call Replace on the StringBuilder 3 times.
Result: It is faster to use a string directly when calling Replace. Even on a longer string, it appears string Replace is faster in 2020.
C# program that benchmarks StringBuilder Replace using System; using System.Diagnostics; using System.Text; class Program { const int _max = 1000000; static void Main() { var text = "bird, frog and dog"; var s1 = Stopwatch.StartNew(); // Version 1: use string Replace. for (int i = 0; i < _max; i++) { string result = text; result = result.Replace("bird", "cat"); result = result.Replace("frog", "fox"); result = result.Replace("dog", "fish"); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use StringBuilder. for (int i = 0; i < _max; i++) { var builder = new StringBuilder(text); builder.Replace("bird", "cat"); builder.Replace("frog", "fox"); builder.Replace("dog", "fish"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 150.73 ns Replace (3) 432.99 ns StringBuilder Replace (3)

Optimization, Contains. Replace can be optimized. Suppose in our program many string replacements must be done. But often nothing is changed in actual strings.
Version 1: This is the initial version of the method. It runs 4 Replace calls on the parameter to the method.
Version 2: This version uses the Contains method around all the Replace calls with the specified common string literal.
Contains
Tip: In version 2, the first 2 Replace calls are only run when the common pattern is found. Often the string is searched less.
Result: It is faster to use Contains to reduce the number of replacements needed—fewer searches are done.
C# program that benchmarks Contains with Replace using System; using System.Diagnostics; class Program { static string ReplaceAll(string text) { text = text.Replace("<span>Cat ", "<span>Cats "); text = text.Replace("<span>Clear ", "<span>Clears "); text = text.Replace("<span>Dog ", "<span>Dogs "); text = text.Replace("<span>Draw ", "<span>Draws "); return text; } static string ReplaceAllWithContains(string text) { if (text.Contains("<span>C")) { text = text.Replace("<span>Cat ", "<span>Cats "); text = text.Replace("<span>Clear ", "<span>Clears "); } if (text.Contains("<span>D")) { text = text.Replace("<span>Dog ", "<span>Dogs "); text = text.Replace("<span>Draw ", "<span>Draws "); } return text; } const int _max = 1000000; static void Main() { Console.WriteLine(ReplaceAll("<span>Dog 100</span>")); Console.WriteLine(ReplaceAllWithContains("<span>Dog 100</span>")); var s1 = Stopwatch.StartNew(); // Version 1: use Replace. for (int i = 0; i < _max; i++) { string result = ReplaceAll("<span>Dog 100</span>"); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use Contains and Replace. for (int i = 0; i < _max; i++) { string result = ReplaceAllWithContains("<span>Dog 100</span>"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output <span>Dogs 100</span> <span>Dogs 100</span> 128.76 ns ReplaceAll 98.89 ns ReplaceAllWithContains

Benchmark, changes. Will a Replace call that makes no changes in the string return faster? This helps us design faster programs by giving us more information about how Replace works.
Version 1: This version of the code calls Replace, but the arguments given will cause no change to occur.
Version 2: Here we replace a string that exists inside the input string—so a change does occur.
Result: It is faster to call Replace() when the method does not make a change to the string data. This case is optimized.
C# program that benchmarks Replace, changed strings using System; using System.Diagnostics; class Program { const int _max = 1000000; static void Main() { string test = "bird"; var s1 = Stopwatch.StartNew(); // Version 1: no change made. for (int i = 0; i < _max; i++) { string result = test.Replace("z", "a"); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: changed string. for (int i = 0; i < _max; i++) { string result = test.Replace("b", "a"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 22.24 ns Replace, no change 39.09 ns Replace, changed string

Benchmark, chars. Sometimes, we can use char arguments instead of 1-char strings. We test a program that calls Replace with different kinds of arguments.
Version 1: In this version of the code, we invoke the Replace() method with 2 char arguments.
Char
Version 2: Here we use string arguments to modify the string that is returned by Replace.
Result: Replace calls that use chars are faster. When possible, prefer smaller arguments like char.
C# program that benchmarks Replace arguments using System; using System.Diagnostics; class Program { const int _max = 1000000; static void Main() { string test = "cat"; var s1 = Stopwatch.StartNew(); // Version 1: use char argument. for (int i = 0; i < _max; i++) { string result = test.Replace('c', 'z'); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use string argument. for (int i = 0; i < _max; i++) { string result = test.Replace("c", "z"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 19.85 ns Replace, char 35.60 ns Replace, string

Notes, copying. Replace() creates a string copy each time it is called. This method could be named "CopyAndReplace" instead of Replace.

Split. Often strings contains invalid syntax. We can use Replace to fix incorrect parts of a string before using Split to separate it.Split

Whitespace. We often need to remove or change whitespace in strings, particularly those read in from files. We can handle tabs, spaces and line breaks.WhitespaceRegex.Replace: Spaces

A summary. For strings, Replace always returns a modified copy. It replaces all instances of a match. Replace() is fast in modern versions of .NET.

Home

© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.