ProblemYou need to delete extraneous characters from each end of a string. SolutionUse the String object's Trim() method, passing to it a list of all characters to be deleted. DiscussionThe following example deletes four letters from the head and tail ends of a string. The letters chosen are just for demonstrating how the trim() method works; a real-world example of where this might be handy would be to remove line numbers, colons, or other characters from the beginnings or ends of strings. As shown in Figure 5-23, the following code causes the entire first word ("The") and the last character ("n") to be removed, or trimmed, from the string: Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" Dim trimChars() As Char = {"T"c, "h"c, "e"c, "n"c} Dim result As String = quote.Trim(trimChars) MsgBox(result) Figure 5-23. Trimming specific characters from the head and tail ends of a stringYou do not need to supply the characters in any particular order; all supplied characters will be trimmed. Trimming continues until the first and last characters of the string are something other than those supplied to the trim() method. If you supply no arguments to trim(), all whitespace characters are trimmed instead. If you want to trim certain characters from either the start or end of the string, but not both, use the trimStart() and TRimEnd() methods, respectively. They accept the same character-array argument as the trim() method. See AlsoRecipes 5.14 and 5.16 discuss related techniques. |