Strings.Split(String, String, Int32, CompareMethod) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
回傳一個以零為基礎、一維的陣列,包含指定數量的子字串。
public static string[] Split(string Expression, string Delimiter = " ", int Limit = -1, Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary);
static member Split : string * string * int * Microsoft.VisualBasic.CompareMethod -> string[]
Public Function Split (Expression As String, Optional Delimiter As String = " ", Optional Limit As Integer = -1, Optional Compare As CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary) As String()
參數
- Expression
- String
必須的。
String 包含子字串與分隔符的表達式。
- Delimiter
- String
Optional. 任何用來識別子字串限制的單一字元。 若 Delimiter 省略,則空格字元 (“” ) 即為分隔符。
- Limit
- Int32
Optional. 輸入字串應被拆分的最大子字串數量。 預設值 -1 表示每次出現 Delimiter 該字串時都應分割輸入字串。
- Compare
- CompareMethod
Optional. 數值表示在評估子字串時使用的比較方式。 數值請參見「設定」。
傳回
String 陣列。 若 Expression 是零長度字串(“”), Split 則回傳一個包含零長度字串的單元素陣列。 如果Delimiter是零長度的字串,或它在 中任何地方都不出現ExpressionSplit,則會回傳一個包含整Expression串的單元素陣列。
範例
以下範例示範如何在其空間處分割字串。
Dim testString As String = "Look at these!"
' Returns an array containing "Look", "at", and "these!".
Dim testArray() As String = Split(testString)
以下範例示範如何將多個分隔符串連成一列,並過濾掉空字串。
Dim testString As String = "apple pear banana "
Dim testArray() As String = Split(testString)
' testArray holds {"apple", "", "", "", "pear", "banana", "", ""}
Dim lastNonEmpty As Integer = -1
For i As Integer = 0 To testArray.Length - 1
If testArray(i) <> "" Then
lastNonEmpty += 1
testArray(lastNonEmpty) = testArray(i)
End If
Next
ReDim Preserve testArray(lastNonEmpty)
' testArray now holds {"apple", "pear", "banana"}
備註
預設情況下,當 Limit 等於 -1 時,函式會在 Split 每次分隔符字串出現時拆分輸入字串,並將子字串回傳成陣列。 當參數 Limit 大於零時, Split 函式會在分隔符的前 Limit-1 次處分割字串,並回傳包含所得子字串的陣列。 例如,回 Split("a:b:c", ":") 傳陣列 {"a", "b", "c"},而 Split("a:b:c", ":", 2) 回傳陣列 {"a", "b:c"}。
當 Split 函數遇到兩個分隔符連續出現,或在字串開頭或結尾遇到分隔符時,它會將其解釋為包圍空字串(“”)。 例如,回 Split("xx", "x") 傳包含三個空字串的陣列:一個來自字串起始與第一個「x」之間,一個來自兩個「x」字串之間,以及一個來自最後一個「x」與字串末尾之間的。
下表說明了可選 Delimiter的 、 Limit和 Compare 參數如何改變函數的 Split 行為。
| 分開通話 | 傳回值 |
|---|---|
Split("42, 12, 19") |
{"42," , "12," , "19"} |
Split("42, 12, 19", ", ") |
{"42", "12", "19"} |
Split("42, 12, 19", ", ", 2) |
{"42", "12, 19"} |
Split("192.168.0.1", ".") |
{"192", "168", "0", "1"} |
Split("Alice and Bob", " AND ") |
{「愛麗絲與鮑勃」} |
Split("Alice and Bob", " AND ", ,CompareMethod.Text) |
{「愛麗絲」、「鮑勃」} |
Split("someone@example.com", "@",1) |
{“someone@example.com”} |
Split("someone@example.com", "@",2) |
{「某人」、「example.com」} |
該 Compare 參數可以有以下數值。
| 常數 | 說明 | 價值 |
|---|---|---|
CompareMethod.Binary |
進行二元比較 | 0 |
CompareMethod.Text |
進行文本比較 | 1 |