Recipe 5.21. Trimming Sets of Characters from a String


Problem

You need to delete extraneous characters from each end of a string.

Solution

Use the String object's Trim() method, passing to it a list of all characters to be deleted.

Discussion

The 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 string


You 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 Also

Recipes 5.14 and 5.16 discuss related techniques.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

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