Split a String in Vb. Net

Split a String in Vb. Net

I am trying to split the following into two strings.

"SERVER1.DOMAIN.COM Running"

For this I use the code.

Dim Str As String = "SERVER1.DOMAIN.COM Running"
Dim strarr() As String
strarr = Str.Split(" ")
For Each s As String In strarr
    MsgBox(s)
Next

This works fine, and I get two message boxes with "SERVER1.DOMAIN.COM" and "Running".

The issue that I am having is that some of my initial strings have more than one space.

"SERVER1.DOMAIN.COM        Off"

There are about eight spaces in-between ".COM" and "Off".

How can I separate this string in the same way?

1

3 Answers

Try this

Dim array As String() = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
1

Use this way:

Dim line As String = "SERVER1.DOMAIN.COM Running"
Dim separators() As String = {"Domain:", "Mode:"}
Dim result() As String
result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)

Here's a method using Regex class:

    Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es     not-running"}
    For Each s In str
        Dim regx = New Regex(" +")
        Dim splitString = regx.Split(s)
        Console.WriteLine("Part 1:{0}  |  Part 2:{1}", splitString(0), splitString(1))
    Next

And the LINQ way to do it:

    Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es     not-running"}
    For Each splitString In From s In str Let regx = New Regex(" +") Select regx.Split(s)
        Console.WriteLine("Part 1:{0}  |  Part 2:{1}", splitString(0), splitString(1))
    Next

Your Answer

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

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.