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?
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
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)
' ...
Use List(Of String)
and Iterate:
Dim mylist as List(Of String) = yourstring.Split(",").ToList
For each item in mylist
'Look at your items, Split by Comma into a list
Console.WriteLine(item.ToString)
Next
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With