如何在 vb.net 中将字符串拆分为列表/数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29639052/
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
How to split a string into list/array in vb.net
提问by Huy Zukerman
I have a long string like this:
我有一个像这样的长字符串:
"data source=qa2;initial catalog=rr;persist security info=True;user id=ka;password=lalala;Connection Timeout=60"
And I want to split it let's say to string list, the list should be like:
我想把它拆分成字符串列表,列表应该是这样的:
Dim list As New List(Of String)
list(0) = qa2
List(1) = rr
List(2)= True
List(3) = ka
.......
How do I split it using VB.Net Code?
如何使用 VB.Net 代码拆分它?
采纳答案by Blackwood
You can use String.Split to split the items at the ";" characters and then again to split each item at the "=" character.
您可以使用 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
回答by Steven Doggart
As others have said, String.Split
is the obvious choice. However, since the string appears to be a SQL Server connection string, you may also want to consider using the SqlConnectionStringBuilder
class to parse the connection string. For instance:
正如其他人所说,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)
' ...
回答by Simon M?Kenzie
This is probably overkill, but you could also do this with regular expressions, like so:
这可能有点矫枉过正,但您也可以使用正则表达式来做到这一点,如下所示:
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()