Reputation: 225
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 a 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?
Upvotes: 8
Views: 52293
Reputation: 153
Use List(Of String)
and iterate:
Dim mylist As List(Of String) = yourstring.Split(",").ToList
For Each item As String In mylist
' Look at your items, split by comma into a list
Console.WriteLine(item.ToString)
Next
Upvotes: 5
Reputation: 8694
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()
Upvotes: 2
Reputation: 43743
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:
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)
' ...
Upvotes: 5
Reputation: 4534
You can use String.Split to split the items at the ";" characters and then again to split each item at the "=" character.
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
Upvotes: 13