Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleTrim leading and trailing non-printing ASCII characters from a string in Visual Basic .NET
DescriptionThis example shows how to trim leading and trailing non-printing ASCII characters from a string in Visual Basic .NET.
Keywordstrim, ltrim, rtrim, TrimWhitespace, LTrimWhitespace, RTrimWhitespace, non-printing, ASCII, carriage return, linefeed, line feed
CategoriesStrings, Tips and Tricks
 
The NonprintingChars function returns an array of all of the non-printing 1-byte ASCII characters. These come before " " and after "~".
 
' Return a string containing all
' non-printing, 1-byte ASCII characters.
Private Function NonprintingChars() As Char()
    Const ASC_SPACE As Integer = Asc(" ")
    Const ASC_TILDE As Integer = Asc("~")
    Const NUM_CHARS As Integer = ASC_SPACE + (255 - _
        ASC_TILDE)
    Static chars() As Char = Nothing

    ' Initialize chars.
    If chars Is Nothing Then
        ReDim chars(NUM_CHARS - 1)
        Dim i As Integer
        For i = 0 To ASC_SPACE - 1
            chars(i) = Chr(i)
        Next i
        Dim next_index As Integer = ASC_SPACE
        For i = ASC_TILDE + 1 To 255
            chars(next_index) = Chr(i)
            next_index += 1
        Next i
    End If

    Return chars
End Function
 
The LTrimWhitespace, RTrimWhitespace, and TrimWhitespace functions simply call the string's TrimStart, TrimEnd, and Trim functions, passing them the array of non-printing characters that should be trimmed off.
 
' Remove leading ASCII characters before " " and after "~".
Private Function LTrimWhitespace(ByVal txt As String) As _
    String
    Return txt.TrimStart(NonprintingChars())
End Function

' Remove trailing ASCII characters before " " and after "~".
Private Function RTrimWhitespace(ByVal txt As String) As _
    String
    Return txt.TrimEnd(NonprintingChars())
End Function

' Remove leading and trailing ASCII characters before " "
' and after "~".
Private Function TrimWhitespace(ByVal txt As String) As _
    String
    Return txt.Trim(NonprintingChars())
End Function
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated