2014-05-20 256 views
1

如果我有這樣的字符串:用字符串拆分字符串?

Dim someStr As String 
someStr = "NODE TEST    ACCESS" 

我想用兩個空格分割的字符串。它看起來像Split()函數接受一個字符,而不是一個完整的字符串分裂。

什麼是最簡單的方法來分割一個字符串的字符串(在這種情況下兩個空格)?由兩個或更多的空間分裂很好。我不打算在兩個分裂。

+0

你的意思是兩個空格或兩個以上的空間?在下面看到我對lardymonkey的回答的評論。 – BobRodes

+0

@BobRodes兩個或更多,但不能保證它會超過2或3個空格。 – JBurace

+0

爲了完全清楚,那麼,是否要將每兩個空格拆分爲一個單獨的元素,或者是否希望使用任何數量的空格作爲單個分隔符? – BobRodes

回答

1

如果你不需要讓你可以嘗試使用替代命令與另一單個字符每兩個字符,你可以

Dim someStr As String 
Dim someArray() as String 

someStr = "NODE TEST    ACCESS" 
someArray = split(Replace$(someStr," ","|"),"|") 
+0

有趣的想法,但如果你有十個空間,你會得到五個|字符,並獲得一些數組值和空字符串。我懷疑OP沒有很清楚地解釋自己,意味着兩個或兩個以上的空間。他的「完整的字符串」讓我更加懷疑。 – BobRodes

2

確定拆分更換空間,得到一些澄清後OP的要求,我們需要擴大lardymonkey的想法。所以:

Dim someStr As String 
Dim someArray() as String 
Dim cLen As Integer 'Keep a count of the current characters in the string 

someStr = "NODE TEST    ACCESS" 

'Strip off one space at a time from groups of >2 spaces 
Do 
    cLen = Len(someStr) 
    someStr = Replace(someStr, Space$(3), Space$(2)) 
Loop Until cLen = Len(someStr) 'No more replacements were made in the current iteration 

'Now you can use lardymonkey's idea 
someArray = Split(Replace$(someStr," ","|"),"|") 
+0

我認爲你的意思是'Space $(3),Space $(2)',而不是'Spaces(3),Spaces(2)'? –

+0

糟糕!我其實是指空間功能。之後我通常不會使用$;不好的習慣,因爲VB在內部使用Variant的時候真的不行。謝謝馬克,我解決了它。 – BobRodes

1

到lardymonkey andBoBrodes

的答案稍有變化,爲什麼你會用空格替換成「|」 ?原始字符串可能包含「|」本身這會產生意外結果

,最好由單一的貨物更換雙位:

Private Sub Command1_Click() 
    Dim someStr As String 
    Dim strArray() As String 
    someStr = "NODE TEST    ACCESS" 
    someStr = RemoveDouble(someStr, " ") 
    strArray = Split(someStr, " ") 
End Sub 

Private Function RemoveDouble(strSource As String, strRemove As String) 
    Dim strReturn As String 
    Dim strDouble As String 
    strDouble = strRemove & strRemove 
    strReturn = Replace(strSource, strDouble, strRemove) 
    Do While InStr(strReturn, strDouble) > 0 
    strReturn = Replace(strReturn, strDouble, strRemove) 
    Loop 
    RemoveDouble = strReturn 
End Function 
2

如果我讀了OP的qusetion正確,他們希望在不返回漸漸空虛結果分割字符串。使用正則表達式大大簡化了這一點。首先添加對的引用Microsoft VBScript正則表達式5.5。然後,您可以根據您的具體需求調整以下功能。

請注意,示例中沒有錯誤處理。

Private Function SplitString(ByVal vPattern As String, ByVal vText As String, ByRef Result() As String) As Integer 
    Dim regex As New RegExp 
    Dim colMatches As MatchCollection 
    Dim intMatchCount As Integer 
    Dim i As Integer 

    intMatchCount = 0 
    regex.Pattern = vPattern 
    regex.Global = True 
    regex.IgnoreCase = True 
    Set colMatches = regex.Execute(vText) 
    If regex.Test(vText) = True Then 
     intMatchCount = colMatches.Count 
     ReDim Result(0 To intMatchCount) 
     For i = 0 To intMatchCount - 1 
      Result(i) = colMatches(i).Value 
     Next i 
     Set colMatches = Nothing ' I don't know if this is needed, but playing it safe 
    End If 
    Set regex = Nothing ' I don't know if this is needed, but playing it safe 

    SplitString = intMatchCount 

End Function 

要使用該功能,請在窗體中添加多行文本框和命令按鈕並粘貼到以下代碼中。

Private Sub Command1_Click() 
    Dim aryMatches() As String 
    Dim i As Integer 
    Dim strPattern As String 
    Dim strText As String 

    Text1.Text = "" 
    strPattern = "\w+" 
    strText = "NODE TEST    ACCESS" 
    If SplitString(strPattern, strText, aryMatches) > 0 Then 
     For i = LBound(aryMatches) To UBound(aryMatches) 
      Text1.SelText = aryMatches(i) & vbCrLf 
      Text1.SelStart = Len(Text1.Text) 
     Next i 
    End If 

End Sub 
1

這次是一個完全不同的答案 - 使用更「原始」的VB字符串函數。如果你對這樣的事情感興趣,這大概是Bob Rhode的答案的兩倍。

本質上,我移過字符串,注意兩個或多個空格的位置,然後一次移動一個字符,直到找到非空格。使用這些信息,我們可以從字符串中的正確位置提取子字符串,並將它們複製到預先分配的字符串數組中。我分配在64塊陣列如果我們去上面的數組中元素的個數,我們以64

Private Function SplitOnMultiSpaces2(ByVal someStr As String) As String() 

    Const someStringsChunkLen As Long = 64 
    Dim someStringLen   As Long 
    Dim someStrings()   As String 
    Dim someStringsIndex  As Long 
    Dim multiSpacePos   As Long 
    Dim nextPos     As Long 

    ' Cache the length of the string. 
    someStringLen = Len(someStr) 

    ' Allocate one chunk of elements initially. 
    ReDim someStrings(0 To someStringsChunkLen - 1) 

    ' Point to the first element in the array. 
    someStringsIndex = 0 

    ' Find the first position of more than 1 space. 
    multiSpacePos = InStr(1, someStr, " ", vbBinaryCompare) 

    ' Special case. If no multi spaces were found, then simply return a single string in the array. 
    If multiSpacePos = 0 Then 
     someStrings(0) = someStr 
    Else 
     ' Point the beginning of the next string to the first character in <someStr>. 
     nextPos = 1 
     Do 
      ' Copy the "next string" into the next available array element. 
      someStrings(someStringsIndex) = Mid$(someStr, nextPos, multiSpacePos - nextPos) 

      ' Move to the second space in the multi-spaces, and iterate until we find a non-space (space = ASCII 32). 
      nextPos = multiSpacePos + 1 
      Do 
       If nextPos = someStringLen Then 
        Exit Do 
       End If 
       nextPos = nextPos + 1 
      Loop While AscW(Mid$(someStr, nextPos, 1)) = 32 

      ' We now pointing to the beginning of the next string - or at the end of the string. 
      ' Look for the next multi space. 
      multiSpacePos = InStr(nextPos, someStr, " ", vbBinaryCompare) 

      ' Point to the next array element. 
      someStringsIndex = someStringsIndex + 1 
      ' If this array element points beyond the current upper bound of the array, then add another chunk to the array. 
      ' We look at the remainder from dividing <someStringsIndex> by <someStringsChunkLen>. 
      ' For instance, if this is element 64, then this is 64/64 = 1 remainder 0. 
      ' We can use this simple test because we only resize upwards. 
      If (someStringsIndex Mod someStringsChunkLen) = 0 Then 
       ' e.g. resize upper bound to 64 + 64 - 1 = 127. 
       ReDim Preserve someStrings(0 To someStringsIndex + someStringsChunkLen - 1) 
      End If 
     Loop Until multiSpacePos = 0 

     ' If we aren't at the end of the string, then copy the remaining values. 
     If nextPos <> someStringLen Then 
      someStrings(someStringsIndex) = Mid$(someStr, nextPos) 
     End If 
    End If 

    ' Resize down to the proper size. 
    ReDim Preserve someStrings(0 To someStringsIndex) 

    ' Return the string array. 
    SplitOnMultiSpaces2 = someStrings() 

End Function 
+0

快兩倍,真的嗎?有趣。你有基準嗎?我不是要求防守的;我真的很感興趣。 – BobRodes

2

另一塊重新分配,它只是使用正則表達式與任何字符替換兩個或多個空格然後分割該角色。

  1. 添加對「Microsoft VBScript正則表達式」的引用。
  2. 做這樣的事情:

    Dim a() As String 
    
    With New RegExp 
        .Pattern = "\s{2,}" 
        a = Split(.Replace(someStr, "~"), "~") 
    End With 
    
+0

只需使用'ChrW(&HE1B6)'而不是'〜'或unicode的*私有使用區域(PUA)*中的任何內容來避免衝突。 – wqw

+0

@wqw當然,你是對的。我只是爲了演示目的而保持簡單。 – Bond