O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.9. Inserting Text into a String

Problem

You have some text (either a char or a string value) that needs to be inserted at a specific location inside of a second string.

Solution

Using the Insert instance method of the string class, a string or char can easily be inserted into a string. For example, in the code fragment:

string sourceString = "The Inserted Text is here -><-";

sourceString  = sourceString.Insert(28, "Insert-This");
Console.WriteLine(sourceString);

the string sourceString is inserted between the > and < characters in a second string. The result is:

The Inserted Text is here ->Insert-This<-

Inserting the character in sourceString into a second literal string between the > and < characters is shown here:

string sourceString = "The Inserted Text is here -><-";
char insertChar = '1';

sourceString  = sourceString.Insert(28, Convert.ToString(insertChar));
Console.WriteLine(sourceString);

There is no overloaded method for Insert that takes a char value, so using a string of length one is the next best solution.

Discussion

There are two ways of inserting strings into other strings, unless, of course, you are using the regular expression classes. The first involves using the Insert instance method on the string class. This method is also slower than the others since strings are immutable, and, therefore, a new string object must be created to hold the modified value. In this recipe, the reference to the old string object is then changed to point to the new string object. Note that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required