输入 分隔符 输出
"42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
"42..12..19" new Char[] {'.'} {"42", "", "12", "", "19"}
"Banana" new Char[] {'.'} {"Banana"}
"Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
"Darb\nSmarba" 空 {"Darb", "Smarba"}
示例
下面的代码示例说明如何使用 Split 方法标记字符串。
[Visual Basic]
Imports System
Public Class SplitTest
Public Shared Sub Main()
Dim words As String = "this is a list of words, with: a bit of punctuation."
Dim split As String() = words.Split(New [Char]() {" "c, ","c, "."c, ":"c})
Dim s As String
For Each s In split
If s.Trim() <> "" Then
Console.WriteLine(s)
End If
Next s
End Sub 'Main
End Class 'SplitTest
[C#]
using System;
public class SplitTest {
public static void Main() {
string words = "this is a list of words, with: a bit of punctuation.";
using namespace System;
using namespace System::Collections;
void main()
{
String* words = S"this is a list of words, with: a bit of punctuation.";
Char chars[] = {' ', ', ', '->', ':'};
String* split[] = words->Split(chars);
IEnumerator* myEnum = split->GetEnumerator();
while (myEnum->MoveNext()) {
String* s = __try_cast<String*>(myEnum->Current);
if (!s->Trim()->Equals(S""))
Console::WriteLine(s);
}
}
[JScript]
import System;
public class SplitTest {
public static function Main() : void {
var words : String = "this is a list of words, with: a bit of punctuation.";
var separators : char[] = [' ', ',', '.', ':'];
var split : String [] = words.Split(separators);
for (var i : int in split) {
var s : String = split[i];
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
SplitTest.Main();