Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You want to insert a character or string into another string at a given location.

Solution

Use the String object's Insert() method.

Discussion

The string method Insert() is overloaded to accept either a character or a string to be inserted at a given location. For example, the following Insert() method adds a comma just after the word "thing" in the sample string:

Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" Dim result As String = quote.Insert(19, ","c) MsgBox(result)

Figure 5-16 shows the result of inserting the comma character.

Figure 5-16. Sample string with a character inserted

In this case the character is inserted after the 19th character of the string, or just after the "g" in "thing." You can insert a character in the first position of a string by using position 0, and at the end of a string by using the string's Length value.

The following code inserts the word "definitely " into the sample string. The inserted text includes a space at the end to keep the words spaced correctly in the result:

Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" quote = quote.Insert(23, "definitely ") MsgBox(quote)

The 23rd position in the original string is just after the "s" character in "is not." Figure 5-17 shows the result of this word insertion.

Figure 5-17. Sample string with the word "definitely" (followed by a space) inserted

VB 6 Users' Update

The equivalent VB 6 string manipulations to insert one string into another are not nearly as straightforward or as efficient as using Visual Basic 2005's Insert() method. The following VB 6 line uses two function calls and concatenates three pieces of strings to get the same result:

quote = Left(Quote, 23) & "definitely " & Mid(Quote, 24)

See Also

Recipe 5.18 also discusses text insertions.

Категории