Aug 11, 2011

C# Replace String Examples


You want to replace one substring in a string with another in your C# program. You may need to swap specific characters with other characters or words. Also, see if you can optimize string replacements with StringBuilder. This page has some Replace method examples, and also a real-world example of using StringBuilder Replace, using the C# programming language.
Key points:Replace is an instance method on String. It replaces all instances of the specified string. It returns a copied string. The original string is not changed.

Example 1

Here we see a very simple example of using the string Replace method. Note that you must assign the result of the string Replace method to a new variable. Other Replace methods in the base class library may not require this.

Program that uses Replace [C#]

using System;

class Program
{
    static void Main()
    {
	const string s = "vamsi is scary.";
	Console.WriteLine(s);

	// Note:
	// You must assign the result of Replace to a new string.
	string v = s.Replace("scary", "not scary");
	Console.WriteLine(v);
    }
}

Output

 vamsi is scary.
 vamsi is not scary.

No comments:

Post a Comment