在VB.NET中拆分一个字符串

时间:2013-06-12 07:32:07

标签: vb.net string split

我试图将以下内容分成两个字符串。

"SERVER1.DOMAIN.COM Running"

为此,我使用代码。

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

这很好用,我得到两个带有"SERVER1.DOMAIN.COM""Running"的消息框。

我遇到的问题是我的一些初始字符串有多个空格。

"SERVER1.DOMAIN.COM        Off"

“.COM”和“Off”之间大约有八个空格。

如何以相同方式分隔此字符串?

3 个答案:

答案 0 :(得分:14)

试试这个

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

答案 1 :(得分:2)

使用这种方式:

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

答案 2 :(得分:1)

这是使用Regex类的方法:

    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

LINQ方式:

    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