C# Replace method

The .Replace function is a string method used to replace characters or strings in a string with another character/string else. In its easiest form you would type something like: string.Replace(“replacethistext”,”withthistext”).

Replace(string,string)

String text = "My favourite colour is red.";
string correctedText = text.Replace("red", "green");
Console.WriteLine(text);
Console.WriteLine(correctedText);
Console.ReadKey();

Will result in:
My favourite colour is red.
My favourite colour is green.

Error handling

Beware that you can have two exceptions, both triggering on the string you want to replace. Below you can find example and the exceptions it could throw.

string longText = "Bacon ipsum dolor sit amet salami pork belly tail tongue pancetta, pork loin tri-tip drumstick bresaola shankle. Bacon ham hock pork belly, sausage tri-tip tongue strip steak fatback.";
longText = longText.Replace(null, "ribeye");
Console.WriteLine(longText);
longText = longText.Replace("", "ribeye");
Console.WriteLine(longText);
Console.ReadKey();
ArgumentNullException This exception occurs when the ‘find’ or ‘replace’ value is null. This could happen if you pass strings from somewhere else, and for some reason it did not get instantiated.
ArgumentException Occurs when the replace is an empty string.

Replace with nothing

If you want to remove all occurrences of a defined string in another string, this function is a possibility (and is how I originally discovered this method). It really is quite good at removing, just use empty or null as replace value.

string text = "This is a shortXKDJIDF line of words.";
Console.WriteLine(text.Replace("XKDJIDF", null));
Console.WriteLine(text.Replace("XKDJIDF", ""));
Console.ReadKey();

Will result in:
This is a short line of words.
This is a short line of words.

Performance?

I would dare say that performance issues are negligible when using the Replace function. However I can share with you that overwriting your string with that string.Replace(something, something), is slower than assigning it to a new string.

There also is an interesting article about performance and measurement on dotnetperls.

Sources

  • http://www.dotnetperls.com/replace
  • http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.