#1,005 – Replacing a Substring with a New Substring

You can use the string.Replace method to find and replace a substring of a longer string with a new substring.  Replace is an instance method that acts upon a specified string and returns a new string.

In the example below, we replace every occurrence of “race” with “class”, returning the new string.

            string quote =
@"There's a race of men that don't fit in,
A race that can't sit still;";

            string newQuote = quote.Replace("race", "class");

            Console.WriteLine(string.Format("ORIGINAL:\n{0}", quote));
            Console.WriteLine(string.Format("NEW:\n{0}", newQuote));

1005-001
You can use Replace to remove instances of a particular substring (replacing them with an empty string).

            string quote = "Four awesome score and seven awesome years ago";

            string newQuote = quote.Replace("awesome ", "");

            Console.WriteLine(string.Format("ORIGINAL:\n{0}", quote));
            Console.WriteLine(string.Format("NEW:\n{0}", newQuote));

1005-002

Advertisements