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.
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.
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 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 method is overloaded to
accept all of the built-in types. In addition, the
StringBuilder
object optimizes string insertion by
not making copies of the original string; instead, the original
string is modified.
If we use the StringBuilder
class instead of the
string
class to insert a string, our code appears
as:
StringBuilder sourceString = new StringBuilder("The Inserted Text is here -><-"); sourceString.Insert (28, "Insert-This"); Console.WriteLine(sourceString);
The character insertion example would be changed to the following code:
char charToInsert = '1'; StringBuilder sourceString = new StringBuilder("The Inserted Text is here -><-"); sourceString.Insert (28, charToInsert); Console.WriteLine(sourceString);
Note that when using the StringBuilder
class, you
must also use the System.Text
namespace.