How to Search & Replace Strings with C#

In C#, there’s a really easy method to find an old value in a string and replace it (and all instances of it) with a new value of your choice. This method, aptly named the Replace method, is fairly straightforward to understand. The syntax is as follows:

public string Replace(
    string oldValue,
    string newValue
)

The best way to understand how to use a method, though, is to see it in action. So let’s say that we have the following string:

String a = "My favorite foods are ice cream and pizza";

But maybe you actually hate pizza, and want to change the word “pizza” to “burgers.” Here’s how you would go about doing it:

a = a.Replace("pizza", "burgers");
Console.WriteLine(a);

So the output of the code above would be: “My favorite foods are ice cream and burgers” written to the console.

When using this code, it’s important to remember that what you want to be replaced will be replaced in ALL instances. So if you had pizza written twice in the string above, then it would have been replaced twice by the word burgers, like this:

String a = "Ice cream is my favorite food. I don't like pizza as much as I like ice cream, but I like pizza more than I like hot dogs";

a = a.Replace("pizza", "burgers");
Console.WriteLine(a);

The output of the code above would be: “Ice cream is my favorite food. I don’t like burgers as much as I like ice cream, but I like burgers more than I like hot dogs.”

Finally, there is also a way to use the Replace method to replace something multiple times. So if you want to replace pizza with burgers for the string in the example above, but then decide you want to replace burgers with cookies immediately after. The code to execute that effect would look something like this (assume that a in the example below is the same string as a in the previous example):

a = a.Replace("pizza", "burgers").Replace("burgers", "cookies");
Console.WriteLine(a);

Your final output of the code above would be “Ice cream is my favorite food. I don’t like cookies as much as I like ice cream, but I like cookies more than I like pizza.”

(Apologies if this tutorial has made you hungry.)

The search and replace method is one that is fairly easy to use. Play around with it and see what kind of strings you can create (maybe ones that aren’t all about food), and how many times you can change the same string so that by the end it doesn’t resemble the original string at all.

Loading...