OneBite.Dev - Coding blog in a bite size

Replace A Substring Within A String In C#

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

In this guide, we will explore how to replace a substring within a string in C#. This task is a fundamental concept in programming and is a routine task when manipulating string data.

Code Snippet: String Replacement in C#

string originalString = "Hello, World!";
string modifiedString = originalString.Replace("World", "CSharp");

Console.WriteLine(modifiedString);

The above code will output: “Hello, CSharp!“.

Code Explanation for String Replacement in C#

Let’s dissect the code snippet step by step:

  1. The string “originalString” is declared with the value “Hello, World!“. This is the string in which we want to replace a specific substring “World”.
string originalString = "Hello, World!";
  1. The Replace method of the String class in C# is then used to replace the substring “World” with “CSharp”. The result is a new string because strings in C# are immutable, and so the method does not change the original string. Instead, it returns a new string where the old word has been replaced with the new word.
string modifiedString = originalString.Replace("World", "CSharp");
  1. The last line in our code snippet uses Console.WriteLine to print the modified string. Console.WriteLine outputs the string to the console, thus, in this case, it will print “Hello, CSharp!“.
Console.WriteLine(modifiedString);

And that is all there is to it! The Replace method is very straightforward and useful in string manipulation tasks in C#. Be familiar with it because string replacements are common in programming.

c-sharp