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"
...
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
Imports System.Linq? Added a demo to my answerTrim. As you see also the non-linq version works: dotnetfiddle.net/eEkZJ3Use 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" ]
Another solution is with the use of Regex:
Dim str As String = "('one','two','three')"
str = RegularExpressions.Regex.Replace(str, "\('|'\)", "")
Dim array() As String = RegularExpressions.Regex.Split(str, "','")
If there are spaces to remove then:
Dim str As String = "( 'one','two' , 'three ')"
str = RegularExpressions.Regex.Replace(str, "\s+|\(\s*'|'\s*\)", "")
Dim array() As String = RegularExpressions.Regex.Split(str, "','")
Start with the string as you presented it:
Dim myString As String = "('one','two','three')"
Debug.WriteLine(myString)
Output:
('one','two','three')
Next get rid of the unwanted characters by replacing them with empty quotes (nothingness). The Chr(39) function represents the single quote:
myString = myString.Replace("(", "").Replace(")", "").Replace(Chr(39), "")
Debug.WriteLine(myString)
output:
one,two,three
Next convert it to an array with the .Split() method:
Dim myStringArray() As String = myString.Split(",")
For i As Integer = 0 To myStringArray.Length - 1
Debug.WriteLine(myStringArray(i))
Next i
Output:
one
two
three
This works without any "Imports" statements
"','".