-
Oct 5th, 2017, 12:49 PM
#1
Thread Starter
Addicted Member
Split string
hi i am trying to split a string which consists of
but i only want to split the string at the first instance of ":"
Code:
string = split("HI:bye:yes:no",":")(0) ' Gives me "Hi"
i want Split(1) to contain the rest of the string
-
Oct 5th, 2017, 12:53 PM
#2
Re: Split string
Maybe
Code:
Dim s As String = "HI:bye:yes:no"
Dim p() As String = s.Split(New Char() {":"c}, 2)
-
Oct 5th, 2017, 01:37 PM
#3
Re: Split string
Instead of Split, you could just use IndexOf and Substring. IndexOf gives you the index of the first instance of whatever you pass it, while SubString returns a substring (as you might guess). Trying to force Split to do it is fine, but a waste of time. Strings can't be changed, so when you call Split, you aren't changing the string, you are just creating an array of new strings. You'd have to take the first element from the array, then combine the other elements back together. IndexOf and SubString would be more direct.
My usual boring signature: Nothing
-
Oct 5th, 2017, 03:27 PM
#4
Re: Split string
I'm agree with Shaggy Hiker
Here is the way to do
vb.net Code:
Dim s As String = "HI:bye:yes:no" Dim i As Integer = s.IndexOf(":"c) Dim s1 As String Dim s2 As String If i >= 0 Then s1 = s.Substring(0, i) s2 = s.Substring(i + 1) End If
-
Oct 7th, 2017, 12:11 AM
#5
Re: Split string
Originally Posted by Shaggy Hiker
You'd have to take the first element from the array, then combine the other elements back together. IndexOf and SubString would be more direct.
Actually, that's not true. A number of the overloads of String.Split (which should be used in preference to Split) let you specify a maximum number of parts. If you only want to split on the first occurrence of a character then specify the max number of parts as 2:
vb.net Code:
Dim str = "HI:bye:yes:no" Dim arr = str.Split(":"c, 2)
-
Oct 7th, 2017, 06:36 PM
#6
Re: Split string
I sit corrected. I've never seen that overload.
All I'll say is that it's a darn good thing that cats have nine lives, considering how many ways programmers have to skin them.
My usual boring signature: Nothing
-
Oct 8th, 2017, 08:44 AM
#7
Re: Split string
Originally Posted by dbasnett
Maybe
Code:
Dim s As String = "HI:bye:yes:no"
Dim p() As String = s.Split(New Char() {":"c}, 2)
-
Oct 8th, 2017, 05:55 PM
#8
Re: Split string
@dbasnett, and you managed to get the syntax right, unlike me.
-
Oct 9th, 2017, 04:00 AM
#9
Re: Split string
You almost had it right ... try:
Code:
split("HI:bye:yes:no",":", 2)
Kris
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|