17

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
  • 4
    Use StringSplitOptions.RemoveEmptyEntries. Commented Jun 12, 2013 at 7:34

3 Answers 3

22

Try this

Dim array As String() = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of " ".ToCharArray() you can simply use an array of character literals: strtemp.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).
3

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)

Comments

1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.