我有一個字串陣列:
array()
和
string = "('one','two','three', ...)"
值一二三是示例。該字串可能包含三個以上的單詞。
如何填充 array() :
"one"
"two"
"three"
...
uj5u.com熱心網友回復:
Dim s = "('one','two','three', ...)"
Dim tokens = From token In s.Trim("(", ")").Split(","c)
Select token.Trim("'"c)
Dim array() As String = tokens.ToArray()
記得添加Imports System.Linq
演示:https ://dotnetfiddle.net/Ayy0y1
請注意,沒有必要使用 LINQ,我只是發現它比以下內容更具可讀性:
Dim array As String() = s.Trim("(", ")").Split(","c)
For i As Int32 = 0 To array.Length - 1
array(i) = array(i).Trim("'"c)
Next
uj5u.com熱心網友回復:
使用 String.Split 將起始字串分解為一個填充有拆分項的陣列。
Dim items = "one two three four five"
Dim array = items.Split(" ")
' Outputs array = [ "one", "two", "three", "four", "five" ]
uj5u.com熱心網友回復:
另一種解決方案是使用正則運算式:
Dim str As String = "('one','two','three')"
str = RegularExpressions.Regex.Replace(str, "\('|'\)", "")
Dim array() As String = RegularExpressions.Regex.Split(str, "','")
如果有空格要洗掉,那么:
Dim str As String = "( 'one','two' , 'three ')"
str = RegularExpressions.Regex.Replace(str, "\s |\(\s*'|'\s*\)", "")
Dim array() As String = RegularExpressions.Regex.Split(str, "','")
uj5u.com熱心網友回復:
從您呈現的字串開始:
Dim myString As String = "('one','two','three')"
Debug.WriteLine(myString)
輸出:
('one','two','three')
接下來通過用空引號(虛無)替換不需要的字符來擺脫它們。Chr(39) 函式表示單引號:
myString = myString.Replace("(", "").Replace(")", "").Replace(Chr(39), "")
Debug.WriteLine(myString)
輸出:
one,two,three
接下來使用 .Split() 方法將其轉換為陣列:
Dim myStringArray() As String = myString.Split(",")
For i As Integer = 0 To myStringArray.Length - 1
Debug.WriteLine(myStringArray(i))
Next i
輸出:
one
two
three
這在沒有任何“匯入”陳述句的情況下有效
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/434531.html
