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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25184019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:15:11  来源:igfitidea点击:

Trim all types of whitespace, including tabs

stringvb6trim

提问by MatthewHagemann

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.

在 VB6 中,Trim() 函数修剪字符串前后的空格。我想知道是否有一个函数不仅可以修剪空格,还可以修剪字符串两端的所有空格(在这种情况下是制表符)。

采纳答案by MatthewHagemann

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

回答by C-Pound Guru

You'll have to combine the Trimfunction with the Replacefunction:

您必须将Trim函数与Replace函数结合起来:

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

你应该结束 ABC{space}{space}{tab}a

回答by Bob77

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 Declareto define the API calls.

如果您使用类型库而不是Declare定义 API 调用,它会很快,甚至更快。

回答by Ovidiu Luca

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.

您可以简单地在 toRemove 字符串中添加要删除的字符。

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.

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

回答by Fabrice T

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

这也可能很有用,@MathewHagemann 的继续它删除前后的空行

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

回答by Affiliate Switchblade

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

回答by Gordon Smith

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

对于 vb.net(非常相似)从前面删除所有空格和控制字符:

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

注意。作为 ByRef 传递以避免制作副本的开销,其他人可能更喜欢编码为 Sub 或传递 ByVal

回答by felix

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 ...."

“制表符&空格&制表符&制表符&换行符&空格&制表符&换行符....”