
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
52
|
Chapter 2: Strings and Characters
the string sourceString is inserted between the > and < characters in a second string.
The result is:
The Inserted Text is here ->Insert-This<-
Inserting a single character into sourceString 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 converting the
char to 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 mod-
ified value. In this recipe, the reference to the old
string object is then changed to
point to the new
string object. Note that the Insert method leaves the original
string untouched and creates a new string object with the inserted characters.
To add flexibility and speed to your string insertions, use the
Insert instance method
on the
StringBuilder class. This