OneBite.Dev - Coding blog in a bite size

Replace Multiple Words In A String In C#

Code snippet for how to Replace Multiple Words In A String In C# with sample and detail explanation

Replacing multiple words in a string is a common operation in programming and application development. In this article, we will walk you through how you can achieve this in C#.

Code snippet for Replacing Multiple Words in a String

Let’s assume we have a sentence “the cat chased the dog” and you want to replace ‘cat’ with ‘mouse’ and ‘dog’ with ‘elephant’. Below is a simple C# code snippet to replace multiple words in a string:

string sentence = "the cat chased the dog";    
Dictionary<string, string> replacements = new Dictionary<string, string>
{
    {"cat", "mouse"},
    {"dog", "elephant"}
};

foreach (KeyValuePair<string, string> pair in replacements)
{
    sentence = sentence.Replace(pair.Key, pair.Value);
}

Console.WriteLine(sentence);

When you run this code, it will output: “the mouse chased the elephant”.

Code Explanation for Replacing Multiple Words in a String

Let’s break down this code to understand what is happening:

  1. Initialization of Variables: we start by defining the original string and the words to be replaced along with their replacements. We store our replacements in a Dictionary data structure where the word to be replaced is the key and the replacement word is the value.
string sentence = "the cat chased the dog";    
Dictionary<string, string> replacements = new Dictionary<string, string>
{
    {"cat", "mouse"},
    {"dog", "elephant"}
};

2.** Replacement of words**: C# provides a built-in method Replace() for string objects. We use this method in a loop to replace each word in the sentence. Replace() method accepts 2 parameters- the old word to be replaced (pair.Key) and the new word (pair.Value).

foreach (KeyValuePair<string, string> pair in replacements)
{
    sentence = sentence.Replace(pair.Key, pair.Value);
}

3.Print the updated sentence: Lastly, we print out the updated sentence. This will print: “the mouse chased the elephant”.

Console.WriteLine(sentence);

In conclusion, by using the built-in Replace() method within a loop, we can easily substitute multiple words within a string in C#. It is a simple yet powerful way to manipulate strings in your application.

c-sharp