C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: The first argument to Replace is the substring we wish to change into something else in the source string.
Argument 2: This is the value we want to use as the replacement in the source string. So the result may contain this substring.
Program: We call replace on a string literal. Replace() returns a new string object. We write this string to the Console with WriteLine.
ConsoleC# program that uses Replace
using System;
class Program
{
static void Main()
{
const string input = "key tool";
Console.WriteLine("::BEFORE::");
Console.WriteLine(input);
// Replace word (and following space) with a new word.
// ... We assign to the Replace method's result.
string output = input.Replace("key ", "keyword ");
Console.WriteLine("::AFTER::");
Console.WriteLine(output);
}
}
Output
::BEFORE::
key tool
::AFTER::
keyword tool
Here: The console program replaces the substring "green" with the substring "brown." There is no need to call Replace() 2 times.
Note: A second Replace() would not do anything. It would just result in CPU cycles being wasted.
C# program that causes multiple replacements
using System;
class Program
{
static void Main()
{
const string value = "The frog is green and the tree is green.";
Console.WriteLine("BEFORE: " + value);
// Store the result of Replace() in a variable.
// ... All instances of the substring are replaced (not just the first).
string modified = value.Replace("green", "brown");
Console.WriteLine("AFTER: " + modified);
}
}
Output
BEFORE: The frog is green and the tree is green.
AFTER: The frog is brown and the tree is brown.
Here: In this example, we create a StringBuilder. We use the constructor to initialize the StringBuilder with a short sentence.
StringBuilderReplace: We replace the word "This" with the word "Here." The result has the new word in place of the old word.
C# program that uses StringBuilder
using System;
using System.Text;
class Program
{
static void Main()
{
const string value = "This is an example.";
// Create new StringBuilder from string.
StringBuilder builder = new StringBuilder(value);
Console.WriteLine("A: " + builder);
// Replace the first word.
// ... The result doesn't need assignment.
builder.Replace("This", "Here");
Console.WriteLine("B: " + builder);
// Insert the string at the beginning.
builder.Insert(0, "Sentence: ");
Console.WriteLine("C: " + builder);
}
}
Output
A: This is an example.
B: Here is an example.
C: Sentence: Here is an example.
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.
Note: It makes no sense to replace an empty string—would the result (in some cases) be an infinitely long string?
ArgumentExceptionC# 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 ...
Tip: Consider IsNullOrEmpty to test for empty or null strings—an empty string will not need replacements.
IsNullOrEmpty, IsNullOrWhiteSpaceC# 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 ...
Version 1: This version ends up creating many string copies. It replaces whitespace around punctuation.
Environment.NewLineEmpty StringVersion 2: MinifyWithStringBuilder is similar but uses StringBuilder. It does the same replacements as version 1.
Result: The version that avoids copies, with StringBuilder, is many times faster.
Tip: Consider a for-loop that tests each char, then appends to a char array or skips the char. This is hard to maintain and test.
C# program that benchmarks Replace methods
using System;
using System.Diagnostics;
using System.Text;
class Program
{
static string MinifyWithString(string text)
{
// Use string Replace to remove whitespace.
text = text.Replace(" ", string.Empty);
text = text.Replace(Environment.NewLine, string.Empty);
text = text.Replace("\\t", string.Empty);
text = text.Replace(" {", "{");
text = text.Replace("{ ", "{");
text = text.Replace(" :", ":");
text = text.Replace(": ", ":");
text = text.Replace(", ", ",");
text = text.Replace("; ", ";");
text = text.Replace(";}", "}");
return text;
}
static string MinifyWithStringBuilder(string text)
{
// Use StringBuilder Replace to remove whitespace.
StringBuilder builder = new StringBuilder(text);
builder.Replace(" ", string.Empty);
builder.Replace(Environment.NewLine, string.Empty);
builder.Replace("\\t", string.Empty);
builder.Replace(" {", "{");
builder.Replace("{ ", "{");
builder.Replace(" :", ":");
builder.Replace(": ", ":");
builder.Replace(", ", ",");
builder.Replace("; ", ";");
builder.Replace(";}", "}");
return builder.ToString();
}
const int _max = 1000000;
static void Main()
{
const string text = "#paragraph { color: black; width: 90%; }";
Console.WriteLine(MinifyWithString(text));
Console.WriteLine(MinifyWithStringBuilder(text));
// Version 1: use string Replace repeatedly.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
MinifyWithString(text);
}
s1.Stop();
// Version 2: use StringBuilder Replace() repeatedly.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
MinifyWithStringBuilder(text);
}
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
#paragraph{color:black;width:90%}
#paragraph{color:black;width:90%}
1055.00 ns string Replace()
2023.33 ns StringBuilder Replace()
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
Version 1: In this version of the code, we invoke the Replace() method with 2 char arguments.
CharVersion 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
Version A: This is the initial version of the method. It runs 4 Replace calls on the formal parameter to the method.
Version B: The second version uses the Contains method around all the Replace calls with the specified common string literal.
ContainsTip: In version B, the first two Replace calls are only run when the common pattern is found. Often the string is searched less.
First version of method: C#
static string A(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;
}
Second version of method: C#
static string B(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;
}
Quote: 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: Microsoft Docs