Split 函数
返回一个从零开始的一维数组,其中包含指定数量的子字符串。
Function Split( ByVal Expression As String, Optional ByVal Delimiter As String = " ", Optional ByVal Limit As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary ) As String()
参数
-
Expression
-
必选。String 表达式,包含子字符串和分隔符。
-
Delimiter
-
可选。用于标识子字符串的界限的任何单个字符。如果省略了 Delimiter,则假定空白字符 (" ") 为分隔符。
-
Limit
-
可选。输入字符串应拆分到的子字符串的最大数量。默认值为 –1,指示在 Delimiter 字符串的每个匹配项处都拆分输入字符串。
-
Compare
-
可选。数值,指示计算子字符串时使用的比较模式。请参见“设置”了解具体的值。
常数 | 说明 | 值 |
---|---|---|
CompareMethod.Binary | 执行二进制比较 | 0 |
CompareMethod.Text | 执行文本比较 | 1 |
默认情况下,或 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 ") | {"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"} |
下面的示例演示如何在字符串的空格处拆分该字符串。
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"}
命名空间: Microsoft.VisualBasic
模块: Strings
程序集: Visual Basic Runtime Library(在 Microsoft.VisualBasic.dll 中)