如何在vb.net中将字符串拆分为列表/数组

时间:2015-04-14 23:25:10

标签: vb.net

我有一个像这样的长字符串:

"data source=qa2;initial catalog=rr;persist security info=True;user id=ka;password=lalala;Connection Timeout=60"

我想分开它,让我们对字符串列表说,列表应该是这样的:

Dim list As New List(Of String)
list(0) = qa2
List(1) = rr
List(2)= True
List(3) = ka
.......

如何使用VB.Net Code拆分它?

3 个答案:

答案 0 :(得分:5)

正如其他人所说,String.Split是显而易见的选择。但是,由于字符串似乎是SQL Server连接字符串,您可能还需要考虑使用SqlConnectionStringBuilder类来解析连接字符串。例如:

Dim builder As New SqlConnectionStringBuilder("data source=qa2;initial catalog=rr;persist security info=True;user id=ka;password=lalala;Connection Timeout=60")
Console.WriteLine("Data Source: " & builder.DataSource)
Console.WriteLine("Initial Catalog: " & builder.InitialCatalog)
' ...

答案 1 :(得分:4)

您可以使用String.Split将项目拆分为“;”字符,然后再次以“=”字符分割每个项目。

Dim str As String = "data source=qa2;initial catalog=rr;persist security info=True;user id=ka;password=lalala;Connection Timeout=60"
Dim items() As String = str.Split(";"c)
Dim list As New List(Of String)
For i As Integer = 0 To items.Length - 1
    Dim elems() As String = items(i).Split("="c)
    If elems.Length > 1 Then list.Add(elems(1).Trim) Else list.Add("")
Next

答案 2 :(得分:2)

这可能有些过分,但您也可以使用正则表达式执行此操作,如下所示:

Imports System.Text.RegularExpressions
Imports System.Linq

' ...

Dim str As String = "data source=qa2;initial catalog=rr;persist security info=True;user id=ka;password=lalala;Connection Timeout=60"

Dim values As String() = Regex.Match(str, "(.+?=(?<value>.+?)(;|$))+") _
    .Groups("value").Captures.Cast(Of Capture).Select(Function(c) (c.Value)).ToArray()