#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: