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 ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.