Split method => what to do with more than one space
Hi,
I'm able of splitting a string lik "Hallo, my name is.." with the "split method"
But what to do if there are more than one space between the words????
split(string, " ") only works if there's exactly one space between them... I've been searching for a couple of houres now
Anyone who can help?
Re: Split method => what to do with more than one space
What about doing a replace on the string first?
VB Code:
Dim splitStrings() As String
Dim myString As String = "Hello World! My name is Lil Ms Squirrel"
myString = myString.Replace(" ", " ") 'replace any double spaces with a single space
splitStrings = myString.Split(" ")
Re: Split method => what to do with more than one space
[QUOTE=Wirloff]Hi,
split(string, " ") only works if there's exactly one space between them...
QUOTE]
Hi,
What do you mean ? It still works and puts the second space of a pair on it's own into one of the array elements
Re: Split method => what to do with more than one space
Quote:
Originally Posted by Lil Ms Squirrel
What about doing a replace on the string first?
VB Code:
Dim splitStrings() As String
Dim myString As String = "Hello World! My name is Lil Ms Squirrel"
myString = myString.Replace(" ", " ") 'replace any double spaces with a single space
splitStrings = myString.Split(" ")
then squish that into 1 line of code :bigyello:
VB Code:
Dim splitStrings() As String = "Hello World! My name is Lil Ms Squirrel".Replace(" ", " ").Split(" "c)
Re: Split method => what to do with more than one space
That's ok but it gets a bit messy when you get text with loads of spaces and not just 2.
If you had a string containing 10 consecutive spaces then you'd have to call replace 9 times!! Not very efficient!
Ignore multiple spaces completely, no replace required...
(look at the string this time!)
VB Code:
Dim splitStrings(), temp() As String
Dim myString As String = [B]"Hello World! My name is Lil Ms Squirrel"[/B]
temp = myString.Split(" "c)
Dim i, j, upper As Integer
upper = temp.Length - 1
splitStrings = New String(upper) {} 'create another string array with same no. of elements
'copy all the actual words to the new array (don't copy any empty strings)
j = -1
For i = 0 To upper
If temp(i).Length > 0 Then 'not empty?
j += 1
splitStrings(j) = temp(i)
End If
Next i
temp = Nothing 'scrap the teporary array that has loads of empty strings in it
If j >= 0 Then
ReDim Preserve splitStrings(j) 'shrink the clean data array to fit the number of actual words found
End If
[B]'do something with splitstrings here[/B]
Re: Split method => what to do with more than one space
woss you could just do this though
VB Code:
Dim myString As String = "Hello World! My name is Lil Ms Squirrel"
Do Until myString.IndexOf(" ") = -1
myString = myString.Replace(" ", " ")
Loop
because im bored i did a speed test on them and they are neck and neck, but this code even finished slightly faster on a few high loop runs...