Home > Software engineering >  (Visual Basic) How to split a string value into an array of strings?
(Visual Basic) How to split a string value into an array of strings?

Time:02-25

I have an array of strings:

array()

and

string = "('one','two','three', ...)"

The values one two three are examples. The string may have more than three words.

How can I fill the array() with:

"one"
"two"
"three"
...

CodePudding user response:

Dim s = "('one','two','three', ...)"
Dim tokens = From token In s.Trim("(", ")").Split(","c)
             Select token.Trim("'"c)
Dim array() As String = tokens.ToArray()

Remember to add Imports System.Linq

Demo: https://dotnetfiddle.net/Ayy0y1

Note that it's not necessary to use LINQ, i just found it more readable than:

Dim array As String() = s.Trim("(", ")").Split(","c)
For i As Int32 = 0 To array.Length - 1
    array(i) = array(i).Trim("'"c)
Next

CodePudding user response:

Use String.Split to break up the starting string into an array populated with the split items.

Dim items = "one two three four five"
Dim array = items.Split(" ")
' Outputs array = [ "one", "two", "three", "four", "five" ]
  • Related