Recipe2.9.Inserting Text into a String


Recipe 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 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 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 you use the StringBuilder class instead of the String class to insert a string, your code appears as:

 StringBuilder sourceString =   new StringBuilder("The Inserted Text is here -><-"); sourceString.Insert (28, "Insert-This"); Console.WriteLine(sourceString); 

The character insertion example changes 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.

See Also

See the "String.Insert Method" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net