修剪所有类型的空白,包括制表符

Mat*_*ann 11 string vb6 trim

在VB6中,Trim()函数修剪字符串前后的空格.我想知道是否有一个函数不仅会修剪空格,而是修剪字符串每一端的所有空格(在本例中为制表符).

C-P*_*uru 7

你必须将Trim功能与Replace功能结合起来:

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

MsgBox Len(Trim$(s))

s = Replace$(Trim$(s), vbTab, "")
MsgBox Len(s)
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码也会删除嵌入的标签.可能可以使用正则表达式来解决这个问题,但这里只能通过循环来修剪空格/制表符:

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
Run Code Online (Sandbox Code Playgroud)

你应该最终得到 ABC{space}{space}{tab}a

  • 不会删除字符串中的所有**标签吗?包括那些内部而不仅仅是最终的内部! (3认同)

小智 5

我使用这个功能:

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
Run Code Online (Sandbox Code Playgroud)

用法:

    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.|
Run Code Online (Sandbox Code Playgroud)

您只需在 toRemove 字符串中添加要删除的字符即可。

它不会一次又一次地复制部分修剪过的字符串,而是搜索修剪过的字符串的开始和结束位置,并仅返回该部分。


Mat*_*ann 2

遗憾的是没有内置功能。这是我写的。它确实有效。

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
Run Code Online (Sandbox Code Playgroud)