string 在 VB.NET 中拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17059971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:58:17  来源:igfitidea点击:

Split a string in VB.NET

vb.netstringsplit

提问by Matt Leyland

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".

这很好用,我得到两个带有"SERVER1.DOMAIN.COM"和 的消息框"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".

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

How can I separate this string in the same way?

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

回答by Sachin

Try this

尝试这个

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

回答by Jayram

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)

回答by bbqchickenrobot

Here's a method using Regex class:

这是使用 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

And the LINQ way to do it:

和 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