Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into list/array in vb.net

Tags:

vb.net

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?

like image 958
Huy Zukerman Avatar asked Apr 14 '15 23:04

Huy Zukerman


4 Answers

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
like image 98
Blackwood Avatar answered Oct 26 '22 12:10

Blackwood


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)
' ...
like image 37
Steven Doggart Avatar answered Oct 26 '22 12:10

Steven Doggart


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
like image 20
Byte Avatar answered Oct 26 '22 14:10

Byte


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()
like image 20
Simon MᶜKenzie Avatar answered Oct 26 '22 13:10

Simon MᶜKenzie