Strings.Split(String, String, Int32, CompareMethod) 方法

定義

傳回以零起始的一維陣列,其中包含指定之子字串數目。

public static string[] Split (string? Expression, string? Delimiter = " ", int Limit = -1, Microsoft.VisualBasic.CompareMethod Compare = Microsoft.VisualBasic.CompareMethod.Binary);
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

選擇性。 用來識別子字串限制的單一字元。 如果省略 Delimiter,則會假設空白字元 (" ") 為分隔符號。

Limit
Int32

選擇性。 輸入字串應該分割之子字串數目的最大值。 預設為 -1,表示應該在每次遇到 Delimiter 字串時即分割輸入字串。

Compare
CompareMethod

選擇性。 數值,表示在評估子字串時要使用的比較。 如需有關值的資訊,請參閱<設定>。

傳回

String[]

String 陣列。 如果 Expression 是長度為零的字串 (""),Split 會傳回包含長度為零的字串之單一元素陣列。 如果 Delimiter 是長度為零的字串,或是未出現在 Expression 內的任何位置,則 Split 會傳回單一元素陣列,其中包含整個 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"}

備註

根據預設,或等於 -1 時 Limit ,函 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」 和字串結尾。

下表示范選擇性 DelimiterLimitCompare 參數如何變更函式的行為 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 ") {“Alice and Bob”}
Split("Alice and Bob", " AND ", ,CompareMethod.Text) {“Alice”, “Bob”}
Split("someone@example.com", "@",1) {"someone@example.com"}
Split("someone@example.com", "@",2) {“someone”, “example.com”}

Compare 變數可以有下列值。

常數 描述
CompareMethod.Binary 執行二進位比較 0
CompareMethod.Text 執行文字比較 1

適用於

另請參閱