tags:

views:

68

answers:

2

Hello,

How do I split a string "99 Stack Overflow" into 2 in vb.net

I want the first value to be 99 and the 2nd to be Stack Overflow.

Please help

+3  A: 

This should do it:

result = yourstring.Split(new Char() { " "c}, 2)

More here. (I think that's how you write a literal Char array in VB.Net; I'm not much of a VB.Net guy, most of what I do in .Net is in C#.

If I'm wrong about how you right literal char arrays and you can't figure it out, you can use a version of it that takes a String instead:

result = yourstring.Split(" ", 2, StringSplitOptions.None)

Details on that one here.

T.J. Crowder
Good suggestion, but it would need to be Split(" "c, 2), to use the character literal. There are two overloads that use a string literal, but neither matches this signature.
John M Gant
@jmgant: In c# you'd need the c after the " " for a character literal, in vb.net what T.J. posted would be acceptable, not sure about the second part though.
Jeff Keslinke
@Jeff, you got that backwards (sorta). In C# it would be ' ' for char and " " for string. VB uses " " for string literals and " "c for char literals.
John M Gant
@jmgant: The second form takes a string, which is why I edited the answer to include it -- the first form takes a `Char()` as its first parameter, and not being much of a VB.Net guy, I don't immediately know how to write a character array literal in VB.net. If you do, edits welcome. :-)
T.J. Crowder
@jmgant: I think I found it (how to write a `Char()` literal). Hard to find an example that isn't an initializer!
T.J. Crowder
@T.J. I see what you mean. I misread the Intellisense, thinking it was looking for a char instead of a char(). Both of your examples are correct.
John M Gant
@jmgant: Cheers.
T.J. Crowder
+1  A: 

Assuming you mean numbers, then a space, then more text, you could use a regular expression to do that.

Dim input As String = "99 Stack Overflow"
Dim re As New Regex("^(\d+) (.+)$")
Dim m As Match = re.Match(input)
Dim firstPart As String
Dim secondPart As String
If m.Success AndAlso m.Groups.Count = 3 Then
    firstPart = m.Groups(1).ToString()
    secondPart = m.Groups(2).ToString()
Else
    'Do something useful'
End If

If you just mean text, a space, and more text, regex is overkill and T.J. Crowder's suggestion is better.

John M Gant