4

When I split a string with many spaces, is there a way to skip blank spaces?

Example string below:

Lorem                            ipsum dolor sit amet, consectetur
             adipiscing elit. Morbi cursus quam sapien, sed ultricies diam vestibulum ac.
Morbi                    luctus nisl eleifend                    mi tincidunt, 
sed vehicula magna lobortis. 

When split, the array contains many positions of " " (blank spaces)

[0] Lorem
[1] " "
[2] " "
[3] " "
[4] " "
[5] Ipsum

So, is there a way to skip this blank spaces and get something like this?

[0] Lorem
[1] Ipsum
[3] dolor

Here's my code:

strTmp = split(tmpstr," ")
For each text in strTmp
'Here I validate other things
  If InStr(x,textToFind) Then
    print "text found"
  Else
    print "not found"
  End If
Next

3 Answers3

3

One of the way is to process the string before splitting it.

Sample Code

varStr = "Lorem                            ipsum dolor sit amet, consectetur             adipiscing elit. Morbi cursus quam sapien, sed ultricies diam vestibulum ac. Morbi                    luctus nisl eleifend                    mi tincidunt, sed vehicula magna lobortis"

' this is what you are getting right now
arrStr = Split(varStr, " ")

Set objRegEx = CreateObject("VBScript.RegExp")
With objRegEx
    .Global = True
    .MultiLine = True
    .Pattern = "\s+" 'matches any whitespace character
    varStr1 = objRegEx.Replace(varStr, "¬")
End With
Set objRegEx = Nothing

' this is what you want
arrStr1 = Split(varStr1, "¬")

I have first stripped all spaces and replaced it with a single ¬ which will act as a delim when I split the string later on.

Pankaj Jaju
  • 5,371
  • 2
  • 25
  • 41
1

Can do a loop on the string, and replace double spaces with single spaces

Do Until InStr(text, "  ") = 0
        text= Replace(text, "  ", " ")
    Loop
Marker
  • 560
  • 4
  • 20
0

You can try this

If trim(text) <> "" Then
Else
End if

Or

If len(trim(text)) > 0 Then
Else
End if
Suriya
  • 85
  • 1
  • 6
  • isnt trim for outside the string only? – Marker May 25 '18 at 17:48
  • After you do the split and when you loop through the array items, you can ignore the empty ones using this. If you do not want the empty array items itself, then you may try to get rid of the extra spaces before the split. – Suriya May 25 '18 at 17:51