1

If I have a string like:

Dim someStr As String
someStr = "NODE TEST              ACCESS"

I want to split that string by two spaces. It looks like the Split() function accepts a character and not a full string for what to split on.

What's the most simple way to split a string by a string (two spaces in this case)? Splitting by two or more spaces is fine. I'm not looking to split at exactly two.

6
  • Do you mean two spaces or two or more spaces? See my comment to lardymonkey's answer below.
    – BobRodes
    May 20, 2014 at 20:58
  • @BobRodes Two or more, but there's no guarantee it'll be more than say 2 or 3 spaces.
    – JBurace
    May 20, 2014 at 20:59
  • Just to be entirely clear, then, do you want to split every two spaces into a separate element, or do you want to use any number of spaces over one as a single delimiter?
    – BobRodes
    May 20, 2014 at 21:02
  • @BobRodes Ah okay. Two or more is fine, it doesn't have to split every 2 spaces.
    – JBurace
    May 20, 2014 at 21:04
  • Maybe you can use regular-expressions.info/vb.html May 20, 2014 at 21:20

6 Answers 6

2

If I am reading the OP's qusetion correctly they want to split the string without getting empty results in the return. Using regular expressions greatly simplifies this. First add a reference to Microsoft VBScript Regular Expressions 5.5. Then you can adapt the function below to your specific needs.

Note there is no error handling in the example.

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

To use the function add a multi-line textbox and a command button to a form and paste in the following code.

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
2

Just use a regex to replace two or more spaces with any character and then split on that character.

  1. Add a reference to "Microsoft VBScript Regular Expressions".
  2. Do something like this:

    Dim a() As String
    
    With New RegExp
        .Pattern = "\s{2,}"
        a = Split(.Replace(someStr, "~"), "~")
    End With
    
2
  • Just use ChrW(&HE1B6) instead of the ~ or anything else from unicode's Private Use Area (PUA) to be safe from collisions.
    – wqw
    May 22, 2014 at 22:03
  • @wqw You're right, of course. I was just trying to keep it simple for demonstration purposes.
    – Bond
    May 23, 2014 at 0:22
2

Ok, after getting a few clarifications to the OP's requirements, we will need to augment lardymonkey's idea a bit. So:

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,"  ","|"),"|")
2
  • I take it that you mean Space$(3), Space$(2), not Spaces(3), Spaces(2) ? May 22, 2014 at 9:07
  • Oops! I actually meant the Space function. I don't usually use the $ afterwards; bad habit really since VB uses a Variant internally when you don't. Thanks Mark, I fixed it.
    – BobRodes
    May 22, 2014 at 17:14
1

If you don't need to keep the spaces you could try using the replace command to replace every two characters with another single character that you can split on

Dim someStr As String
Dim someArray() as String

someStr = "NODE TEST              ACCESS"
someArray = split(Replace$(someStr,"  ","|"),"|")
1
  • Interesting idea, but if you have ten spaces you will get five | characters, and get some array values with empty strings in them. I suspect the OP hasn't explained himself quite clearly, and means two or more spaces. His "full string" makes me even more suspicious.
    – BobRodes
    May 20, 2014 at 20:57
1

a slight change to the answers of lardymonkey andBoBrodes

why would you replace the spaces with "|" ? the original string could contain "|" by itself which would give unexpected results

it's better to replace the double spaces by single ones :

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
1

This time, a completely different answer - using the more "primitive" VB string functions. If you are interested in such things, this is roughly twice as fast as Bob Rhode's answer.

Essentially, I move through the string, noting the positions of two or more spaces, and then move one character at a time until a non-space is found. Using this information, we can pull substrings out from the correct position in the string, and copy them into a pre-allocated string array. I allocate the array in chunks of 64. If we go above the number of elements in the array, we reallocate it by another chunk of 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
1
  • Twice as fast, really? Interesting. Did you benchmark that? I'm not asking defensively; I'm genuninely interested.
    – BobRodes
    May 22, 2014 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.