ProblemYou want to insert a character or string into another string at a given location. SolutionUse the String object's Insert() method. DiscussionThe 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 insertedIn 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
See AlsoRecipe 5.18 also discusses text insertions. |