Trim all types of whitespace, including tabs

2020-08-17 08:31发布

问题:

In VB6, the Trim() function trims spaces off the front and back of a string. I am wondering if there is a function that will trim not just spaces, but all whitespace (tabs in this case) off of each end of a string.

回答1:

You'll have to combine the Trim function with the Replace function:

s = "   ABC  " & vbTab & "   "
MsgBox Len(s)

MsgBox Len(Trim$(s))

s = Replace$(Trim$(s), vbTab, "")
MsgBox Len(s)

Note: The above code will also remove embedded tabs. Probably can resolve this with regular expressions but here's a way to trim spaces/tabs only from the ends via looping:

Dim s As String, char As String, trimmedString As String
Dim x As Integer

s = "  " & vbTab & " ABC  " & vbTab & "a   " & vbTab

'// Trim all spaces/tabs from the beginning
For x = 1 To Len(s)
    char = Mid$(s, x, 1)
    If char = vbTab Or char = " " Then
    Else
        trimmedString = Mid$(s, x)
        Exit For
    End If
Next
'// Now do it from the end
For x = Len(trimmedString) To 1 Step -1
    char = Mid$(trimmedString, x, 1)
    If char = vbTab Or char = " " Then
    Else
        trimmedString = Left$(trimmedString, x)
        Exit For
    End If
Next

You should end up with ABC{space}{space}{tab}a



回答2:

It's a shame there is no built in function. Here is the one I wrote. It does the trick.

Function TrimAllWhitespace(ByVal str As String)

    str = Trim(str)

    Do Until Not Left(str, 1) = Chr(9)
        str = Trim(Mid(str, 2, Len(str) - 1))
    Loop

    Do Until Not Right(str, 1) = Chr(9)
        str = Trim(Left(str, Len(str) - 1))
    Loop

    TrimAllWhitespace = str

End Function


回答3:

How about:

Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenW" ( _
    ByVal lpString As Long) As Long

Private Declare Function StrTrim Lib "shlwapi" Alias "StrTrimW" ( _
    ByVal pszSource As Long, _
    ByVal pszTrimChars As Long) As Long

Private Function TrimWS(ByVal Text As String) As String
    'Unicode-safe.
    Const WHITE_SPACE As String = " " & vbTab & vbCr & vbLf

    If StrTrim(StrPtr(Text), StrPtr(WHITE_SPACE)) Then
        TrimWS = Left$(Text, lstrlen(StrPtr(Text)))
    Else
        TrimWS = Text
    End If
End Function

It is fast, and even faster if you use typelibs instead of Declare to define the API calls.



回答4:

I use this function:

Private Function TrimAll(Text As String) As String

Const toRemove As String = " " & vbTab & vbCr & vbLf 'what to remove

Dim s As Long: s = 1
Dim e As Long: e = Len(Text)
Dim c As String

If e = 0 Then Exit Function 'zero len string

Do 'how many chars to skip on the left side
    c = Mid(Text, s, 1)
    If c = "" Or InStr(1, toRemove, c) = 0 Then Exit Do
    s = s + 1
Loop
Do 'how many chars to skip on the right side
    c = Mid(Text, e, 1)
    If e = 1 Or InStr(1, toRemove, c) = 0 Then Exit Do
    e = e - 1
Loop
TrimAll = Mid(Text, s, (e - s) + 1) 'return remaining text

End Function

Usage:

    Debug.Print "|" & TrimAll("") & "|" 'prints ||
    Debug.Print "|" & TrimAll(" ") & "|" 'prints ||
    Debug.Print "|" & TrimAll("a") & "|" 'prints |a|
    Debug.Print "|" & TrimAll("a ") & "|" 'prints |a|
    Debug.Print "|" & TrimAll(" a") & "|" 'prints |a|
    Debug.Print "|" & TrimAll(" a b ") & "|" 'prints |a b|
    Debug.Print "|" & TrimAll(vbTab & " " & "Some " & vbCrLf & " text. " & vbCrLf & " ") & "|" 'prints |Some
text.|

You can simply add the chars to be removed at the toRemove string.

It does not copy the partialy trimmed string again and again, but rather searches where the trimmed string starts and ends, and returns that portion only.



回答5:

This could also be useful, a continue of @MathewHagemann It remove empties lines before and after

Public Function TrimAllWhitespace(ByVal str As String)

    str = Trim(str)

    Do Until Not Left(str, 1) = Chr(9)
        str = Trim(Mid(str, 2, Len(str) - 1))
    Loop

    Do Until Not Right(str, 1) = Chr(9)
        str = Trim(Left(str, Len(str) - 1))
    Loop

    Do Until Not Left(str, 1) = Chr(13)
        str = Trim(Mid(str, 2, Len(str) - 1))
    Loop

    Do Until Not Left(str, 1) = Chr(10)
        str = Trim(Mid(str, 2, Len(str) - 1))
    Loop

    Do Until Not Right(str, 1) = Chr(10)
        str = Trim(Left(str, Len(str) - 1))
    Loop

    Do Until Not Right(str, 1) = Chr(13)
        str = Trim(Left(str, Len(str) - 1))
    Loop

    TrimAllWhitespace = str

End Function


回答6:

Here is something I came up with that lets you choose between returning the trimmed string itself or the length of the trimmed string

in a module

'=========================================================
'this function lets get either the len of a string with spaces and tabs trimmed of
'or get the string itself with the spaces and tabs trimmed off
'=========================================================
Public Property Get eLen(sStr As String, Optional bTrimTabs As Boolean = True, Optional bReturnLen As Boolean = True) As Variant

'function which trims away spaces and tabs (if [bTrimTabs] is set to True)
Dim s As String:             s = sfuncTrimEnds(sStr, bTrimTabs)

If bReturnLen Then ' if [bReturnLen] = True then return the trimmed string len
       eLen = Len(s)

Else ' if [bReturnLen] = False then return the trimmed string
       eLen = s
End If

End Property

'===============================================================
' this function trims spaces from both sides of string and tabs if  [bTrimTabs] = true
' the return value is the string with the spaces (and tabs) trimmed off both sides
'===============================================================
Private Function sfuncTrimEnds(ByVal sStr As String, Optional bTrimTabs As Boolean = True) As String



Dim lStart As Long, lEnd As Long
Dim sChr As String

Dim llen As Long:             llen = Len(sStr)
Dim l As Long:                For l = 1 To llen
                                            sChr = Mid$(sStr, l, 1)

                                            If sChr <> " " And sChr <> vbTab Then
                                                                 lStart = l
                                                                 Exit For
                                            End If
                               Next l

                               For l = llen To 1 Step -1
                                                   sChr = Mid$(sStr, l, 1)

                                                   If sChr <> " " And sChr <> vbTab Then
                                                                 lEnd = l
                                                                 Exit For
                                                   End If
                               Next l

                               sStr = Mid$(sStr, lStart, (lEnd -     (lStart - 1)))

sfuncTrimEnds = sStr

End Function

To use this:

Dim s As String:         s = "   " & vbTab & " " & "mary wants my little lamb  " & "   " & vbTab & " "
MsgBox Tru.eLen(s, , False) 'will return the trimmed text
MsgBox Tru.eLen(s)   ' will return the len of the trimmed text

OR

       Dim sVal As String:            sVal = Tru.eLen(s, , False)
                                      if len(sval) > 0 then ' yada yada


回答7:

For vb.net (very similar) to remove all whitespace and control characters from front:

Public Function TrimWspFromFront(ByRef MyStr As String) As String
    While MyStr.Length > 0 AndAlso Left(MyStr, 1) < " "
        MyStr = Trim(Right(MyStr, MyStr.Length - 1))
    End While
    Return MyStr
End Function

To remove from rear:

Public Function TrimWspFromEnd(ByRef MyStr As String) As String
    While MyStr.Length > 0 AndAlso Right(MyStr, 1) < " "
        MyStr = Trim(Left(MyStr, MyStr.Length - 1))
    End While
    Return MyStr
End Function

NB. Passed as ByRef to avoid overhead of making a copy, others may prefer to code as a Sub or pass ByVal



回答8:

better not forget to iterate the function it self as there might be a sequence of tabs whitspaces and line breaks in not ordered manner and you would like to clean all of them.

"tab & space & tab & tab & linebreak & space & tab & linebrea ...."



标签: string vb6 trim