C# program to replace a substring in another string

C# program to replace a substring in another string:

In this post, we will learn how to replace a substring with a different string in a given string.

C# string class provides one method called Replace that can be used to replace a substring in a string. This program will show you how to use Replace method with examples.

Definition of Replace:

Replace is defined as below:

public String Replace(String old, String new)

This is a public method defined in String class and we can call it on any string object. It will replace all occurrences of old with new in the original String. Since string is immutable, it will create one new string and return it.

Exceptions:

Replace method may throw any of the below two exceptions:

ArgumentNullException : It is thrown if any of the provided string is null. ArgumentException : If any of the provided string is an empty string

Example of Replace:

Let’s take a look at the below program:

using System;

public class Program
{
	public static void Main()
	{
		String givenString = "Hello World";
		String newString = givenString.Replace("World", "Hello");
		
		Console.WriteLine(newString);
	}
}

Here,

  • givenString is the original string.
  • We called Replace on givenString to replace World with Hello.

It will replace the word World with Hello and print the below string:

Hello Hello

You might also like: