String.Split Method (System) (2024)

Edit

Share via

  • Reference

Definition

Namespace:
System
Assembly:
System.Runtime.dll
Assembly:
netstandard.dll
Assembly:
mscorlib.dll

Important

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

Overloads

Split(String, Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

Split(Char[], Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

Split(Char, Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options.Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

Split(String[], StringSplitOptions)

Splits a string into substrings based on a specified delimiting string and, optionally, options.

Split(String, StringSplitOptions)

Splits a string into substrings that are based on the provided string separator.

Split(Char[])

Splits a string into substrings based on specified delimiting characters.

Split(Char[], Int32)

Splits a string into a maximum number of substrings based on specified delimiting characters.

Split(Char, StringSplitOptions)

Splits a string into substrings based on a specified delimiting character and, optionally, options.

Split(ReadOnlySpan<Char>)

Splits a string into substrings based on specified delimiting characters.

Split(String[], Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

Split(Char[], StringSplitOptions)

Splits a string into substrings based on specified delimiting characters and options.

Remarks

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to specify whether to include empty strings and/or trim substrings in the result (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods), or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

Tip

The Split method is not always the best way to break a delimited string into substrings. If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method. For more information, see Extract substrings from a string.

Example

The following examples show three different overloads of String.Split(). The first example calls the Split(Char[]) overload and passes in a single delimiter.

string s = "You win some. You lose some.";string[] subs = s.Split(' ');foreach (var sub in subs){ Console.WriteLine($"Substring: {sub}");}// This example produces the following output://// Substring: You// Substring: win// Substring: some.// Substring: You// Substring: lose// Substring: some.
let s = "You win some. You lose some."let subs = s.Split ' 'for sub in subs do printfn $"Substring: {sub}"// This example produces the following output://// Substring: You// Substring: win// Substring: some.// Substring: You// Substring: lose// Substring: some.
Dim s As String = "You win some. You lose some."Dim subs As String() = s.Split()For Each substring As String In subs Console.WriteLine($"Substring: {substring}")Next' This example produces the following output:'' Substring: You' Substring: win' Substring: some.' Substring: You' Substring: lose' Substring: some.

As you can see, the period characters (.) are included in two of the substrings. If you want to exclude the period characters, you can add the period character as an additional delimiting character. The next example shows how to do this.

string s = "You win some. You lose some.";string[] subs = s.Split(' ', '.');foreach (var sub in subs){ Console.WriteLine($"Substring: {sub}");}// This example produces the following output://// Substring: You// Substring: win// Substring: some// Substring:// Substring: You// Substring: lose// Substring: some// Substring:
let s = "You win some. You lose some."let subs = s.Split(' ', '.')for sub in subs do printfn $"Substring: {sub}"// This example produces the following output://// Substring: You// Substring: win// Substring: some// Substring:// Substring: You// Substring: lose// Substring: some// Substring:
Dim s As String = "You win some. You lose some."Dim subs As String() = s.Split(" "c, "."c)For Each substring As String In subs Console.WriteLine($"Substring: {substring}")Next' This example produces the following output:'' Substring: You' Substring: win' Substring: some' Substring:' Substring: You' Substring: lose' Substring: some' Substring:

The periods are gone from the substrings, but now two extra empty substrings have been included. These empty substring represent the substring between a word and the period that follows it. To omit empty substrings from the resulting array, you can call theSplit(Char[], StringSplitOptions) overload and specifyStringSplitOptions.RemoveEmptyEntries for the options parameter.

string s = "You win some. You lose some.";char[] separators = new char[] { ' ', '.' };string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);foreach (var sub in subs){ Console.WriteLine($"Substring: {sub}");}// This example produces the following output://// Substring: You// Substring: win// Substring: some// Substring: You// Substring: lose// Substring: some
let s = "You win some. You lose some."let separators = [| ' '; '.' |]let subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)for sub in subs do printfn $"Substring: {sub}"// This example produces the following output://// Substring: You// Substring: win// Substring: some// Substring: You// Substring: lose// Substring: some
Dim s As String = "You win some. You lose some."Dim separators As Char() = New Char() {" "c, "."c}Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)For Each substring As String In subs Console.WriteLine($"Substring: {substring}")Next' This example produces the following output:'' Substring: You' Substring: win' Substring: some' Substring: You' Substring: lose' Substring: some

The sections for the individual overloads of String.Split() contain further examples.

Split(String, Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

public string[] Split (string? separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * int * StringSplitOptions -> string[]
Public Function Split (separator As String, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parameters

separator
String

A string that delimits the substrings in this instance.

count
Int32

The maximum number of elements expected in the array.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array that contains at most count substrings from this instance that are delimited by separator.

Remarks

If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

Applies to

Split(Char[], Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

public: cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count, StringSplitOptions options);
public string[] Split (char[] separator, int count, StringSplitOptions options);
public string[] Split (char[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]public string[] Split (char[] separator, int count, StringSplitOptions options);
member this.Split : char[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]member this.Split : char[] * int * StringSplitOptions -> string[]
Public Function Split (separator As Char(), count As Integer, options As StringSplitOptions) As String()

Parameters

separator
Char[]

An array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

The maximum number of substrings to return.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array that contains the substrings in this string that are delimited by one or more characters in separator. For more information, see the Remarks section.

Attributes

Exceptions

count is negative.

options is not one of the StringSplitOptions values.

Examples

The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// This example demonstrates the String.Split(Char[], Boolean) and // String.Split(Char[], Int32, Boolean) methodsusing namespace System;void Show( array<String^>^entries ){ Console::WriteLine( "The return value contains these {0} elements:", entries->Length ); System::Collections::IEnumerator^ myEnum = entries->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ entry = safe_cast<String^>(myEnum->Current); Console::Write( "<{0}>", entry ); } Console::Write( "{0}{0}", Environment::NewLine );}int main(){ String^ s = ",one,,,two,,,,,three,,"; array<Char>^sep = gcnew array<Char>{ ',' }; array<String^>^result; // Console::WriteLine( "The original string is \"{0}\".", s ); Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] ); Console::WriteLine(); // Console::WriteLine( "Split the string and return all elements:" ); result = s->Split( sep, StringSplitOptions::None ); Show( result ); // Console::WriteLine( "Split the string and return all non-empty elements:" ); result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries ); Show( result ); // Console::WriteLine( "Split the string and return 2 elements:" ); result = s->Split( sep, 2, StringSplitOptions::None ); Show( result ); // Console::WriteLine( "Split the string and return 2 non-empty elements:" ); result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries ); Show( result );}/*This example produces the following results:The original string is ",one,,,two,,,,,three,,".The separation character is ','.Split the string and return all elements:The return value contains these 12 elements:<><one><><><two><><><><><three><><>Split the string and return all non-empty elements:The return value contains these 3 elements:<one><two><three>Split the string and return 2 elements:The return value contains these 2 elements:<><one,,,two,,,,,three,,>Split the string and return 2 non-empty elements:The return value contains these 2 elements:<one><,,two,,,,,three,,>*/
// This example demonstrates the String.Split() methods that use// the StringSplitOptions enumeration.// Example 1: Split a string delimited by charactersConsole.WriteLine("1) Split a string delimited by characters:\n");string s1 = ",ONE,, TWO,, , THREE,,";char[] charSeparators = new char[] { ',' };string[] result;Console.WriteLine($"The original string is: \"{s1}\".");Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");// Split the string and return all elementsConsole.WriteLine("1a) Return all elements:");result = s1.Split(charSeparators, StringSplitOptions.None);Show(result);// Split the string and return all elements with whitespace trimmedConsole.WriteLine("1b) Return all elements with whitespace trimmed:");result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);Show(result);// Split the string and return all non-empty elementsConsole.WriteLine("1c) Return all non-empty elements:");result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string and return all non-whitespace elements with whitespace trimmedConsole.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Split the string into only two elements, keeping the remainder in the last matchConsole.WriteLine("1e) Split into only two elements:");result = s1.Split(charSeparators, 2, StringSplitOptions.None);Show(result);// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("1f) Split into only two elements with whitespace trimmed:");result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);Show(result);// Split the string into only two non-empty elements, keeping the remainder in the last matchConsole.WriteLine("1g) Split into only two non-empty elements:");result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Example 2: Split a string delimited by another stringConsole.WriteLine("2) Split a string delimited by another string:\n");string s2 = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] ";string[] stringSeparators = new string[] { "[stop]" };Console.WriteLine($"The original string is: \"{s2}\".");Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");// Split the string and return all elementsConsole.WriteLine("2a) Return all elements:");result = s2.Split(stringSeparators, StringSplitOptions.None);Show(result);// Split the string and return all elements with whitespace trimmedConsole.WriteLine("2b) Return all elements with whitespace trimmed:");result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);Show(result);// Split the string and return all non-empty elementsConsole.WriteLine("2c) Return all non-empty elements:");result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string and return all non-whitespace elements with whitespace trimmedConsole.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Split the string into only two elements, keeping the remainder in the last matchConsole.WriteLine("2e) Split into only two elements:");result = s2.Split(stringSeparators, 2, StringSplitOptions.None);Show(result);// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("2f) Split into only two elements with whitespace trimmed:");result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);Show(result);// Split the string into only two non-empty elements, keeping the remainder in the last matchConsole.WriteLine("2g) Split into only two non-empty elements:");result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Display the array of separated strings using a local functionvoid Show(string[] entries){ Console.WriteLine($"The return value contains these {entries.Length} elements:"); foreach (string entry in entries) { Console.Write($"<{entry}>"); } Console.Write("\n\n");}/*This example produces the following results:1) Split a string delimited by characters:The original string is: ",ONE,, TWO,, , THREE,,".The delimiter character is: ','.1a) Return all elements:The return value contains these 9 elements:<><ONE><>< TWO><>< >< THREE><><>1b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>1c) Return all non-empty elements:The return value contains these 4 elements:<ONE>< TWO>< >< THREE>1d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>1e) Split into only two elements:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< TWO,, , THREE,,>1h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO,, , THREE,,>2) Split a string delimited by another string:The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".The delimiter string is: "[stop]".2a) Return all elements:The return value contains these 9 elements:<><ONE>< ><TWO ><>< ><THREE><>< >2b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>2c) Return all non-empty elements:The return value contains these 6 elements:<ONE>< ><TWO >< ><THREE>< >2d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>2e) Split into only two elements:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>2g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>*/
// This example demonstrates the String.Split() methods that use// the StringSplitOptions enumeration.// Display the array of separated strings using a local functionlet show (entries: string[]) = printfn $"The return value contains these {entries.Length} elements:" for entry in entries do printf $"<{entry}>" printf "\n\n"// Example 1: Split a string delimited by charactersprintfn "1) Split a string delimited by characters:\n"let s1 = ",ONE,, TWO,, , THREE,,"let charSeparators = [| ',' |]printfn $"The original string is: \"{s1}\"."printfn $"The delimiter character is: '{charSeparators[0]}'.\n"// Split the string and return all elementsprintfn "1a) Return all elements:"let result = s1.Split(charSeparators, StringSplitOptions.None)show result// Split the string and return all elements with whitespace trimmedprintfn "1b) Return all elements with whitespace trimmed:"let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)show result// Split the string and return all non-empty elementsprintfn "1c) Return all non-empty elements:"let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)show result// Split the string and return all non-whitespace elements with whitespace trimmedprintfn "1d) Return all non-whitespace elements with whitespace trimmed:"let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Split the string into only two elements, keeping the remainder in the last matchprintfn "1e) Split into only two elements:"let result = s1.Split(charSeparators, 2, StringSplitOptions.None)show result// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchprintfn "1f) Split into only two elements with whitespace trimmed:"let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)show result// Split the string into only two non-empty elements, keeping the remainder in the last matchprintfn "1g) Split into only two non-empty elements:"let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)show result// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchprintfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Example 2: Split a string delimited by another stringprintfn "2) Split a string delimited by another string:\n"let s2 = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] "let stringSeparators = [| "[stop]" |]printfn $"The original string is: \"{s2}\"."printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"// Split the string and return all elementsprintfn "2a) Return all elements:"let result = s2.Split(stringSeparators, StringSplitOptions.None)show result// Split the string and return all elements with whitespace trimmedprintfn "2b) Return all elements with whitespace trimmed:"let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)show result// Split the string and return all non-empty elementsprintfn "2c) Return all non-empty elements:"let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)show result// Split the string and return all non-whitespace elements with whitespace trimmedprintfn "2d) Return all non-whitespace elements with whitespace trimmed:"let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Split the string into only two elements, keeping the remainder in the last matchprintfn "2e) Split into only two elements:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)show result// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchprintfn "2f) Split into only two elements with whitespace trimmed:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)show result// Split the string into only two non-empty elements, keeping the remainder in the last matchprintfn "2g) Split into only two non-empty elements:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)show result// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchprintfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result(*This example produces the following results:1) Split a string delimited by characters:The original string is: ",ONE,, TWO,, , THREE,,".The delimiter character is: ','.1a) Return all elements:The return value contains these 9 elements:<><ONE><>< TWO><>< >< THREE><><>1b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>1c) Return all non-empty elements:The return value contains these 4 elements:<ONE>< TWO>< >< THREE>1d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>1e) Split into only two elements:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< TWO,, , THREE,,>1h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO,, , THREE,,>2) Split a string delimited by another string:The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".The delimiter string is: "[stop]".2a) Return all elements:The return value contains these 9 elements:<><ONE>< ><TWO ><>< ><THREE><>< >2b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>2c) Return all non-empty elements:The return value contains these 6 elements:<ONE>< ><TWO >< ><THREE>< >2d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>2e) Split into only two elements:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>2g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>*)
Public Shared Sub StringSplitOptionsExamples() ' This example demonstrates the String.Split() methods that use ' the StringSplitOptions enumeration. ' Example 1: Split a string delimited by characters Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf) Dim s1 As String = ",ONE,, TWO,, , THREE,," Dim charSeparators() As Char = {","c} Dim result() As String Console.WriteLine("The original string is: ""{0}"".", s1) Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0)) ' Split the string and return all elements Console.WriteLine("1a) Return all elements:") result = s1.Split(charSeparators, StringSplitOptions.None) Show(result) ' Split the string and return all elements with whitespace trimmed Console.WriteLine("1b) Return all elements with whitespace trimmed:") result = s1.Split(charSeparators, StringSplitOptions.TrimEntries) Show(result) ' Split the string and return all non-empty elements Console.WriteLine("1c) Return all non-empty elements:") result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string and return all non-whitespace elements with whitespace trimmed Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:") result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two elements, keeping the remainder in the last match Console.WriteLine("1e) Split into only two elements:") result = s1.Split(charSeparators, 2, StringSplitOptions.None) Show(result) ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("1f) Split into only two elements with whitespace trimmed:") result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two non-empty elements, keeping the remainder in the last match Console.WriteLine("1g) Split into only two non-empty elements:") result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:") result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Example 2: Split a string delimited by another string Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf) Dim s2 As String = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] " Dim stringSeparators() As String = {"[stop]"} Console.WriteLine("The original string is: ""{0}"".", s2) Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0)) ' Split the string and return all elements Console.WriteLine("2a) Return all elements:") result = s2.Split(stringSeparators, StringSplitOptions.None) Show(result) ' Split the string and return all elements with whitespace trimmed Console.WriteLine("2b) Return all elements with whitespace trimmed:") result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries) Show(result) ' Split the string and return all non-empty elements Console.WriteLine("2c) Return all non-empty elements:") result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string and return all non-whitespace elements with whitespace trimmed Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:") result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two elements, keeping the remainder in the last match Console.WriteLine("2e) Split into only two elements:") result = s2.Split(stringSeparators, 2, StringSplitOptions.None) Show(result) ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("2f) Split into only two elements with whitespace trimmed:") result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two non-empty elements, keeping the remainder in the last match Console.WriteLine("2g) Split into only two non-empty elements:") result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:") result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result)End Sub' Display the array of separated strings.Public Shared Sub Show(ByVal entries() As String) Console.WriteLine("The return value contains these {0} elements:", entries.Length) Dim entry As String For Each entry In entries Console.Write("<{0}>", entry) Next entry Console.Write(vbCrLf & vbCrLf)End Sub'This example produces the following results:'' 1) Split a string delimited by characters:'' The original string is: ",ONE,, TWO,, , THREE,,".' The delimiter character is: ','.'' 1a) Return all elements:' The return value contains these 9 elements:' <><ONE><>< TWO><>< >< THREE><><>'' 1b) Return all elements with whitespace trimmed:' The return value contains these 9 elements:' <><ONE><><TWO><><><THREE><><>'' 1c) Return all non-empty elements:' The return value contains these 4 elements:' <ONE>< TWO>< >< THREE>'' 1d) Return all non-whitespace elements with whitespace trimmed:' The return value contains these 3 elements:' <ONE><TWO><THREE>'' 1e) Split into only two elements:' The return value contains these 2 elements:' <><ONE,, TWO,, , THREE,,>'' 1f) Split into only two elements with whitespace trimmed:' The return value contains these 2 elements:' <><ONE,, TWO,, , THREE,,>'' 1g) Split into only two non-empty elements:' The return value contains these 2 elements:' <ONE>< TWO,, , THREE,,>'' 1h) Split into only two non-whitespace elements with whitespace trimmed:' The return value contains these 2 elements:' <ONE><TWO,, , THREE,,>'' 2) Split a string delimited by another string:'' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".' The delimiter string is: "[stop]".'' 2a) Return all elements:' The return value contains these 9 elements:' <><ONE>< ><TWO ><>< ><THREE><>< >'' 2b) Return all elements with whitespace trimmed:' The return value contains these 9 elements:' <><ONE><><TWO><><><THREE><><>'' 2c) Return all non-empty elements:' The return value contains these 6 elements:' <ONE>< ><TWO >< ><THREE>< >'' 2d) Return all non-whitespace elements with whitespace trimmed:' The return value contains these 3 elements:' <ONE><TWO><THREE>'' 2e) Split into only two elements:' The return value contains these 2 elements:' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >'' 2f) Split into only two elements with whitespace trimmed:' The return value contains these 2 elements:' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>'' 2g) Split into only two non-empty elements:' The return value contains these 2 elements:' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >'' 2h) Split into only two non-whitespace elements with whitespace trimmed:' The return value contains these 2 elements:' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>'

Remarks

Delimiter characters are not included in the elements of the returned array.

If this instance does not contain any of the characters in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

To pass null for the char[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(String[], Int32, StringSplitOptions). The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick brown fox";_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"phrase.Split(Unchecked.defaultof<char[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split(null :> char[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split((null: char[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"Dim words() As Stringwords = phrase.Split(TryCast(Nothing, Char()), 3, StringSplitOptions.RemoveEmptyEntries)words = phrase.Split(New Char() {}, 3, StringSplitOptions.RemoveEmptyEntries)

If the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

Each element of separator defines a separate delimiter character. If the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

Performance considerations

The Split methods allocate memory for the returned array object and a String object for each array element. If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. This significantly reduces the additional overhead of each method call.

Notes to Callers

In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char, Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options.Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

public string[] Split (char separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * int * StringSplitOptions -> string[]
Public Function Split (separator As Char, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parameters

separator
Char

A character that delimits the substrings in this instance.

count
Int32

The maximum number of elements expected in the array.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array that contains at most count substrings from this instance that are delimited by separator.

Remarks

If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

Applies to

Split(String[], StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into substrings based on a specified delimiting string and, optionally, options.

public: cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, StringSplitOptions options);
public string[] Split (string[] separator, StringSplitOptions options);
public string[] Split (string[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]public string[] Split (string[] separator, StringSplitOptions options);
member this.Split : string[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]member this.Split : string[] * StringSplitOptions -> string[]
Public Function Split (separator As String(), options As StringSplitOptions) As String()

Parameters

separator
String[]

An array of strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. For more information, see the Remarks section.

Attributes

Exceptions

options is not one of the StringSplitOptions values.

Examples

The following example illustrates the difference in the arrays returned by calling a string's String.Split(String[], StringSplitOptions) method with its options parameter equal to StringSplitOptions.None and StringSplitOptions.RemoveEmptyEntries.

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";string[] stringSeparators = new string[] { "[stop]" };string[] result;// Display the original string and delimiter string.Console.WriteLine($"Splitting the string:\n \"{source}\".");Console.WriteLine();Console.WriteLine($"Using the delimiter string:\n \"{stringSeparators[0]}\"");Console.WriteLine();// Split a string delimited by another string and return all elements.result = source.Split(stringSeparators, StringSplitOptions.None);Console.WriteLine($"Result including all elements ({result.Length} elements):");Console.Write(" ");foreach (string s in result){ Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);}Console.WriteLine();Console.WriteLine();// Split delimited by another string and return all non-empty elements.result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);Console.WriteLine($"Result including non-empty elements ({result.Length} elements):");Console.Write(" ");foreach (string s in result){ Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);}Console.WriteLine();// The example displays the following output:// Splitting the string:// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".//// Using the delimiter string:// "[stop]"//// Result including all elements (9 elements):// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'//// Result including non-empty elements (3 elements):// 'ONE' 'TWO' 'THREE'
let source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"let stringSeparators = [| "[stop]" |]// Display the original string and delimiter string.printfn $"Splitting the string:\n \"{source}\".\n"printfn $"Using the delimiter string:\n \"{stringSeparators[0]}\"\n"// Split a string delimited by another string and return all elements.let result = source.Split(stringSeparators, StringSplitOptions.None)printfn $"Result including all elements ({result.Length} elements):"printf " "for s in result do printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """printfn "\n"// Split delimited by another string and return all non-empty elements.let result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)Console.WriteLine($"Result including non-empty elements ({result.Length} elements):")printf " "for s in result do printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """printfn ""// The example displays the following output:// Splitting the string:// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".//// Using the delimiter string:// "[stop]"//// let result including all elements (9 elements):// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'//// let result including non-empty elements (3 elements):// 'ONE' 'TWO' 'THREE'
Dim source As String = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"Dim stringSeparators() As String = {"[stop]"}Dim result() As String' Display the original string and delimiter string.Console.WriteLine("Splitting the string:{0} '{1}'.", vbCrLf, source)Console.WriteLine()Console.WriteLine("Using the delimiter string:{0} '{1}'.", vbCrLf, stringSeparators(0))Console.WriteLine()' Split a string delimited by another string and return all elements.result = source.Split(stringSeparators, StringSplitOptions.None)Console.WriteLine("Result including all elements ({0} elements):", result.Length)Console.Write(" ")For Each s As String In result Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))NextConsole.WriteLine()Console.WriteLine()' Split delimited by another string and return all non-empty elements.result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)Console.WriteLine("Result including non-empty elements ({0} elements):", result.Length)Console.Write(" ")For Each s As String In result Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))NextConsole.WriteLine()' The example displays the following output:' Splitting the string:' "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".' ' Using the delimiter string:' "[stop]"' ' Result including all elements (9 elements):' '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'' ' Result including non-empty elements (3 elements):' 'ONE' 'TWO' 'THREE'

The following example defines an array of separators that include punctuation and white-space characters. Passing this array along with a value of StringSplitOptions.RemoveEmptyEntries to the Split(String[], StringSplitOptions) method returns an array that consists of the individual words from the string.

string[] separators = { ",", ".", "!", "?", ";", ":", " " };string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);foreach (var word in words) Console.WriteLine(word);// The example displays the following output:// The// handsome// energetic// young// dog// was// playing// with// his// smaller// more// lethargic// litter// mate
let separators = [| ","; "."; "!"; "?"; ""; ":"; " " |]let value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."let words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)for word in words do printfn $"${word}"// The example displays the following output:// The// handsome// energetic// young// dog// was// playing// with// his// smaller// more// lethargic// litter// mate
 Dim separators() As String = {",", ".", "!", "?", ";", ":", " "} Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate." Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries) For Each word In words Console.WriteLine(word) NextEnd Sub' The example displays the following output:'' The' handsome' energetic' young' dog' was' playing' with' his' smaller' more' lethargic' litter' mate

Note that the method is called with the options argument set to StringSplitOptions.RemoveEmptyEntries. This prevents the returned array from including String.Empty values that represent empty substring matches between punctuation marks and white-space characters.

Remarks

When a string is delimited by a known set of strings, you can use the Split method to separate it into substrings.

Delimiter strings are not included in the elements of the returned array. For example, if the separator array includes the string "--" and the value of the current string instance is "aa--bb--cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.

If the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

Each element of separator defines a separate delimiter that consists of one or more characters. If the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. For example, if separator includes two elements, "-" and "_", the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty, which represents the empty string that precedes the "-" substring at index 0.

  2. String.Empty, which represents the empty string between the "-" substring at index 0 and the "_" substring at index 1.

  3. "aa".

  4. String.Empty, which represents the empty string that follows the "-" substring at index 4.

  5. String.Empty, which represents the empty string that follows the "_" substring at index 5.

The separator array

If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." returns the following four-element array: { "This", "is", "a", "string." }.

If the separator parameter is null or contains no non-empty strings, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

To pass null for the string[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(Char[], StringSplitOptions). The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick brown fox";_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"phrase.Split(Unchecked.defaultof<string[]>, StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split(null :> string[], StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split((null: string[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"Dim words() As Stringwords = phrase.Split(TryCast(Nothing, String()), StringSplitOptions.RemoveEmptyEntries)words = phrase.Split(New String() {}, StringSplitOptions.RemoveEmptyEntries)

Comparison details

The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

The Split method ignores any element of separator whose value is null or the empty string ("").

To avoid ambiguous results when strings in separator have characters in common, the Split operation proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

For example, consider an instance whose value is "abcdef". If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be a string array that contains two elements, "a" and "f". This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be a string array that contains two elements, "a" and "ef". This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be a string array that contains two elements, "a" and "def".

Performance considerations

The Split methods allocate memory for the returned array object and a String object for each array element. If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. This significantly reduces the additional overhead of each method call.

Notes to Callers

In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Applies to

Split(String, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into substrings that are based on the provided string separator.

public string[] Split (string? separator, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * StringSplitOptions -> string[]
Public Function Split (separator As String, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parameters

separator
String

A string that delimits the substrings in this string.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array whose elements contain the substrings from this instance that are delimited by separator.

Applies to

Split(Char[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into substrings based on specified delimiting characters.

public: cli::array <System::String ^> ^ Split(... cli::array <char> ^ separator);
public string[] Split (params char[] separator);
public string[] Split (params char[]? separator);
member this.Split : char[] -> string[]
Public Function Split (ParamArray separator As Char()) As String()

Parameters

separator
Char[]

An array of delimiting characters, an empty array that contains no delimiters, or null.

Returns

An array whose elements contain the substrings from this instance that are delimited by one or more characters in separator. For more information, see the Remarks section.

Examples

The following example demonstrates how to extract individual words from a block of text by treating the space character ( ) and tab character (\t) as delimiters. The string being split includes both of these characters.

string s = "Today\tI'm going to school";string[] subs = s.Split(' ', '\t');foreach (var sub in subs){ Console.WriteLine($"Substring: {sub}");}// This example produces the following output://// Substring: Today// Substring: I'm// Substring: going// Substring: to// Substring: school
let s = "Today\tI'm going to school"let subs = s.Split(' ', '\t')for sub in subs do printfn $"Substring: {sub}"// This example produces the following output://// Substring: Today// Substring: I'm// Substring: going// Substring: to// Substring: school
Dim s As String = "Today" & vbTab & "I'm going to school"Dim subs As String() = s.Split(" "c, Char.Parse(vbTab))For Each substring In subs Console.WriteLine("Substring: " & substring)Next' This example produces the following output:'' Substring: Today' Substring: I 'm' Substring: going' Substring: to' Substring: school

Remarks

When a string is delimited by a known set of characters, you can use the Split(Char[]) method to separate it into substrings.

Delimiter characters are not included in the elements of the returned array. For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding element in the returned array contains Empty.

The following table shows some examples.

LanguageString valueSeparatorReturned array
C#"42, 12, 19"new Char[] {',', ' '}{"42", "", "12", "", "19"}
Visual Basic"42, 12, 19"Char() = {","c, " "c}){"42", "", "12", "", "19"}
C#"42..12..19."new Char[] {'.'}{"42", "", "12", "", "19", ""}
Visual Basic"42..12..19."Char() = {"."c}{"42", "", "12", "", "19", ""}
C#"Banana"new Char[] {'.'}{"Banana"}
Visual Basic"Banana"Char() = {"."c}{"Banana"}
C#"Darb\nSmarba"new Char[] {}{"Darb", "Smarba"}
Visual Basic"Darb" & vbLf & "Smarba"Char() = {}{"Darb", "Smarba"}
C#"Darb\nSmarba"null{"Darb", "Smarba"}
Visual Basic"Darb" & vbLf & "Smarba"Nothing{"Darb", "Smarba"}

The separator array

Each element of separator defines a separate delimiter that consists of a single character.

If the separator argument is null or contains no characters, the method treats white-space characters as the delimiters. White-space characters are defined by the Unicode standard, and the Char.IsWhiteSpace method returns true if a white-space character is passed to it.

String.Split(Char[]) and compiler overload resolution

Although the single parameter for this overload of String.Split is a character array, you can call it with a single character, as the following example shows.

string value = "This is a short string.";char delimiter = 's';string[] substrings = value.Split(delimiter);foreach (var substring in substrings) Console.WriteLine(substring);// The example displays the following output:// Thi// i// a// hort// tring.
let value = "This is a short string."let delimiter = 's'let substrings = value.Split delimiterfor substring in substrings do printfn $"{substring}"// The example displays the following output:// Thi// i// a// hort// tring.
 Dim value As String = "This is a short string." Dim delimiter As Char = "s"c Dim substrings() As String = value.Split(delimiter) For Each substring In substrings Console.WriteLine(substring) NextEnd Sub' The example displays the following output:'' Thi' i' a' hort' tring.

Because the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array. This is not the case for other String.Split overloads that include a separator parameter; you must explicitly pass these overloads a character array as the separator argument.

Comparison details

The Split(Char[]) method extracts the substrings in this string that are delimited by one or more of the characters in the separator array, and returns those substrings as elements of an array.

The Split(Char[]) method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

Performance considerations

The Split methods allocate memory for the returned array object and a String object for each array element. If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method. You also have the option of using the Compare method to locate a substring within a string.

To split a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. To split a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. This significantly reduces the additional overhead of each method call.

Notes to Callers

In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

See also

Applies to

Split(Char[], Int32)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into a maximum number of substrings based on specified delimiting characters.

public: cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count);
public string[] Split (char[] separator, int count);
public string[] Split (char[]? separator, int count);
member this.Split : char[] * int -> string[]
Public Function Split (separator As Char(), count As Integer) As String()

Parameters

separator
Char[]

An array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

The maximum number of substrings to return.

Returns

An array whose elements contain the substrings in this instance that are delimited by one or more characters in separator. For more information, see the Remarks section.

Exceptions

count is negative.

Examples

The following example demonstrates how count can be used to limit the number of strings returned by Split.

string name = "Alex Johnson III";string[] subs = name.Split(null, 2);string firstName = subs[0];string lastName;if (subs.Length > 1){ lastName = subs[1];}// firstName = "Alex"// lastName = "Johnson III"
let name = "Alex Johnson III"let subs = name.Split(null, 2)let firstName = subs[0]let lastName = if subs.Length > 1 then subs[1] else ""// firstName = "Alex"// lastName = "Johnson III"
Console.WriteLine("What is your name?")Dim name As String = Console.ReadLine()Dim substrings = name.Split(" "c, count:=2)Dim firstName As String = substrings(0)Dim lastName As StringIf substrings.Length > 1 Then lastName = substrings(1)End IfConsole.WriteLine("firstName = ""{0}""", firstName)Console.WriteLine("lastName = ""{0}""", lastName)' If the user enters "Alex Johnson III":' firstName = "Alex"' lastName = "Johnson III"

Remarks

Delimiter characters are not included in the elements of the returned array.

If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance. If count is zero, an empty array is returned.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

If there are more than count substrings in this instance, the first count - 1 substrings are returned in the first count - 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

The following table shows some examples.

LanguageString valueSeparatorReturned array
C#"42, 12, 19"new Char[] {',', ' '}{"42", "", "12", "", "19"}
Visual Basic"42, 12, 19"Char() = {","c, " "c}){"42", "", "12", "", "19"}
C#"42..12..19."new Char[] {'.'}{"42", "", "12", "", "19", ""}
Visual Basic"42..12..19."Char() = {"."c}{"42", "", "12", "", "19", ""}
C#"Banana"new Char[] {'.'}{"Banana"}
Visual Basic"Banana"Char() = {"."c}{"Banana"}
C#"Darb\nSmarba"new Char[] {}{"Darb", "Smarba"}
Visual Basic"Darb" & vbLf & "Smarba"Char() = {}{"Darb", "Smarba"}
C#"Darb\nSmarba"null{"Darb", "Smarba"}
Visual Basic"Darb" & vbLf & "Smarba"Nothing{"Darb", "Smarba"}

Performance considerations

The Split methods allocate memory for the returned array object and a String object for each array element. If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. This significantly reduces the additional overhead of each method call.

Notes to Callers

In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

See also

Applies to

Split(Char, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into substrings based on a specified delimiting character and, optionally, options.

public string[] Split (char separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * StringSplitOptions -> string[]
Public Function Split (separator As Char, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parameters

separator
Char

A character that delimits the substrings in this string.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array whose elements contain the substrings from this instance that are delimited by separator.

Applies to

Split(ReadOnlySpan<Char>)

Splits a string into substrings based on specified delimiting characters.

public: cli::array <System::String ^> ^ Split(ReadOnlySpan<char> separator);
public string[] Split (scoped ReadOnlySpan<char> separator);
member this.Split : ReadOnlySpan<char> -> string[]
Public Function Split (separator As ReadOnlySpan(Of Char)) As String()

Parameters

separator
ReadOnlySpan<Char>

A span of delimiting characters, or an empty span that contains no delimiters.

Returns

An array whose elements contain the substrings from this instance that are delimited by one or more characters in separator.

Applies to

Split(String[], Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

public: cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, int count, StringSplitOptions options);
public string[] Split (string[] separator, int count, StringSplitOptions options);
public string[] Split (string[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]public string[] Split (string[] separator, int count, StringSplitOptions options);
member this.Split : string[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]member this.Split : string[] * int * StringSplitOptions -> string[]
Public Function Split (separator As String(), count As Integer, options As StringSplitOptions) As String()

Parameters

separator
String[]

The strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

The maximum number of substrings to return.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. For more information, see the Remarks section.

Attributes

Exceptions

count is negative.

options is not one of the StringSplitOptions values.

Examples

The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// This example demonstrates the String.Split(Char[], Boolean) and // String.Split(Char[], Int32, Boolean) methodsusing namespace System;void Show( array<String^>^entries ){ Console::WriteLine( "The return value contains these {0} elements:", entries->Length ); System::Collections::IEnumerator^ myEnum = entries->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ entry = safe_cast<String^>(myEnum->Current); Console::Write( "<{0}>", entry ); } Console::Write( "{0}{0}", Environment::NewLine );}int main(){ String^ s = ",one,,,two,,,,,three,,"; array<Char>^sep = gcnew array<Char>{ ',' }; array<String^>^result; // Console::WriteLine( "The original string is \"{0}\".", s ); Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] ); Console::WriteLine(); // Console::WriteLine( "Split the string and return all elements:" ); result = s->Split( sep, StringSplitOptions::None ); Show( result ); // Console::WriteLine( "Split the string and return all non-empty elements:" ); result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries ); Show( result ); // Console::WriteLine( "Split the string and return 2 elements:" ); result = s->Split( sep, 2, StringSplitOptions::None ); Show( result ); // Console::WriteLine( "Split the string and return 2 non-empty elements:" ); result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries ); Show( result );}/*This example produces the following results:The original string is ",one,,,two,,,,,three,,".The separation character is ','.Split the string and return all elements:The return value contains these 12 elements:<><one><><><two><><><><><three><><>Split the string and return all non-empty elements:The return value contains these 3 elements:<one><two><three>Split the string and return 2 elements:The return value contains these 2 elements:<><one,,,two,,,,,three,,>Split the string and return 2 non-empty elements:The return value contains these 2 elements:<one><,,two,,,,,three,,>*/
// This example demonstrates the String.Split() methods that use// the StringSplitOptions enumeration.// Example 1: Split a string delimited by charactersConsole.WriteLine("1) Split a string delimited by characters:\n");string s1 = ",ONE,, TWO,, , THREE,,";char[] charSeparators = new char[] { ',' };string[] result;Console.WriteLine($"The original string is: \"{s1}\".");Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");// Split the string and return all elementsConsole.WriteLine("1a) Return all elements:");result = s1.Split(charSeparators, StringSplitOptions.None);Show(result);// Split the string and return all elements with whitespace trimmedConsole.WriteLine("1b) Return all elements with whitespace trimmed:");result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);Show(result);// Split the string and return all non-empty elementsConsole.WriteLine("1c) Return all non-empty elements:");result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string and return all non-whitespace elements with whitespace trimmedConsole.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Split the string into only two elements, keeping the remainder in the last matchConsole.WriteLine("1e) Split into only two elements:");result = s1.Split(charSeparators, 2, StringSplitOptions.None);Show(result);// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("1f) Split into only two elements with whitespace trimmed:");result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);Show(result);// Split the string into only two non-empty elements, keeping the remainder in the last matchConsole.WriteLine("1g) Split into only two non-empty elements:");result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Example 2: Split a string delimited by another stringConsole.WriteLine("2) Split a string delimited by another string:\n");string s2 = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] ";string[] stringSeparators = new string[] { "[stop]" };Console.WriteLine($"The original string is: \"{s2}\".");Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");// Split the string and return all elementsConsole.WriteLine("2a) Return all elements:");result = s2.Split(stringSeparators, StringSplitOptions.None);Show(result);// Split the string and return all elements with whitespace trimmedConsole.WriteLine("2b) Return all elements with whitespace trimmed:");result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);Show(result);// Split the string and return all non-empty elementsConsole.WriteLine("2c) Return all non-empty elements:");result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string and return all non-whitespace elements with whitespace trimmedConsole.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Split the string into only two elements, keeping the remainder in the last matchConsole.WriteLine("2e) Split into only two elements:");result = s2.Split(stringSeparators, 2, StringSplitOptions.None);Show(result);// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("2f) Split into only two elements with whitespace trimmed:");result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);Show(result);// Split the string into only two non-empty elements, keeping the remainder in the last matchConsole.WriteLine("2g) Split into only two non-empty elements:");result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Display the array of separated strings using a local functionvoid Show(string[] entries){ Console.WriteLine($"The return value contains these {entries.Length} elements:"); foreach (string entry in entries) { Console.Write($"<{entry}>"); } Console.Write("\n\n");}/*This example produces the following results:1) Split a string delimited by characters:The original string is: ",ONE,, TWO,, , THREE,,".The delimiter character is: ','.1a) Return all elements:The return value contains these 9 elements:<><ONE><>< TWO><>< >< THREE><><>1b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>1c) Return all non-empty elements:The return value contains these 4 elements:<ONE>< TWO>< >< THREE>1d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>1e) Split into only two elements:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< TWO,, , THREE,,>1h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO,, , THREE,,>2) Split a string delimited by another string:The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".The delimiter string is: "[stop]".2a) Return all elements:The return value contains these 9 elements:<><ONE>< ><TWO ><>< ><THREE><>< >2b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>2c) Return all non-empty elements:The return value contains these 6 elements:<ONE>< ><TWO >< ><THREE>< >2d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>2e) Split into only two elements:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>2g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>*/
// This example demonstrates the String.Split() methods that use// the StringSplitOptions enumeration.// Display the array of separated strings using a local functionlet show (entries: string[]) = printfn $"The return value contains these {entries.Length} elements:" for entry in entries do printf $"<{entry}>" printf "\n\n"// Example 1: Split a string delimited by charactersprintfn "1) Split a string delimited by characters:\n"let s1 = ",ONE,, TWO,, , THREE,,"let charSeparators = [| ',' |]printfn $"The original string is: \"{s1}\"."printfn $"The delimiter character is: '{charSeparators[0]}'.\n"// Split the string and return all elementsprintfn "1a) Return all elements:"let result = s1.Split(charSeparators, StringSplitOptions.None)show result// Split the string and return all elements with whitespace trimmedprintfn "1b) Return all elements with whitespace trimmed:"let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)show result// Split the string and return all non-empty elementsprintfn "1c) Return all non-empty elements:"let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)show result// Split the string and return all non-whitespace elements with whitespace trimmedprintfn "1d) Return all non-whitespace elements with whitespace trimmed:"let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Split the string into only two elements, keeping the remainder in the last matchprintfn "1e) Split into only two elements:"let result = s1.Split(charSeparators, 2, StringSplitOptions.None)show result// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchprintfn "1f) Split into only two elements with whitespace trimmed:"let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)show result// Split the string into only two non-empty elements, keeping the remainder in the last matchprintfn "1g) Split into only two non-empty elements:"let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)show result// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchprintfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Example 2: Split a string delimited by another stringprintfn "2) Split a string delimited by another string:\n"let s2 = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] "let stringSeparators = [| "[stop]" |]printfn $"The original string is: \"{s2}\"."printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"// Split the string and return all elementsprintfn "2a) Return all elements:"let result = s2.Split(stringSeparators, StringSplitOptions.None)show result// Split the string and return all elements with whitespace trimmedprintfn "2b) Return all elements with whitespace trimmed:"let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)show result// Split the string and return all non-empty elementsprintfn "2c) Return all non-empty elements:"let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)show result// Split the string and return all non-whitespace elements with whitespace trimmedprintfn "2d) Return all non-whitespace elements with whitespace trimmed:"let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Split the string into only two elements, keeping the remainder in the last matchprintfn "2e) Split into only two elements:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)show result// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchprintfn "2f) Split into only two elements with whitespace trimmed:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)show result// Split the string into only two non-empty elements, keeping the remainder in the last matchprintfn "2g) Split into only two non-empty elements:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)show result// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchprintfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result(*This example produces the following results:1) Split a string delimited by characters:The original string is: ",ONE,, TWO,, , THREE,,".The delimiter character is: ','.1a) Return all elements:The return value contains these 9 elements:<><ONE><>< TWO><>< >< THREE><><>1b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>1c) Return all non-empty elements:The return value contains these 4 elements:<ONE>< TWO>< >< THREE>1d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>1e) Split into only two elements:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< TWO,, , THREE,,>1h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO,, , THREE,,>2) Split a string delimited by another string:The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".The delimiter string is: "[stop]".2a) Return all elements:The return value contains these 9 elements:<><ONE>< ><TWO ><>< ><THREE><>< >2b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>2c) Return all non-empty elements:The return value contains these 6 elements:<ONE>< ><TWO >< ><THREE>< >2d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>2e) Split into only two elements:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>2g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>*)
Public Shared Sub StringSplitOptionsExamples() ' This example demonstrates the String.Split() methods that use ' the StringSplitOptions enumeration. ' Example 1: Split a string delimited by characters Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf) Dim s1 As String = ",ONE,, TWO,, , THREE,," Dim charSeparators() As Char = {","c} Dim result() As String Console.WriteLine("The original string is: ""{0}"".", s1) Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0)) ' Split the string and return all elements Console.WriteLine("1a) Return all elements:") result = s1.Split(charSeparators, StringSplitOptions.None) Show(result) ' Split the string and return all elements with whitespace trimmed Console.WriteLine("1b) Return all elements with whitespace trimmed:") result = s1.Split(charSeparators, StringSplitOptions.TrimEntries) Show(result) ' Split the string and return all non-empty elements Console.WriteLine("1c) Return all non-empty elements:") result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string and return all non-whitespace elements with whitespace trimmed Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:") result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two elements, keeping the remainder in the last match Console.WriteLine("1e) Split into only two elements:") result = s1.Split(charSeparators, 2, StringSplitOptions.None) Show(result) ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("1f) Split into only two elements with whitespace trimmed:") result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two non-empty elements, keeping the remainder in the last match Console.WriteLine("1g) Split into only two non-empty elements:") result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:") result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Example 2: Split a string delimited by another string Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf) Dim s2 As String = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] " Dim stringSeparators() As String = {"[stop]"} Console.WriteLine("The original string is: ""{0}"".", s2) Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0)) ' Split the string and return all elements Console.WriteLine("2a) Return all elements:") result = s2.Split(stringSeparators, StringSplitOptions.None) Show(result) ' Split the string and return all elements with whitespace trimmed Console.WriteLine("2b) Return all elements with whitespace trimmed:") result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries) Show(result) ' Split the string and return all non-empty elements Console.WriteLine("2c) Return all non-empty elements:") result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string and return all non-whitespace elements with whitespace trimmed Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:") result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two elements, keeping the remainder in the last match Console.WriteLine("2e) Split into only two elements:") result = s2.Split(stringSeparators, 2, StringSplitOptions.None) Show(result) ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("2f) Split into only two elements with whitespace trimmed:") result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two non-empty elements, keeping the remainder in the last match Console.WriteLine("2g) Split into only two non-empty elements:") result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:") result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result)End Sub' Display the array of separated strings.Public Shared Sub Show(ByVal entries() As String) Console.WriteLine("The return value contains these {0} elements:", entries.Length) Dim entry As String For Each entry In entries Console.Write("<{0}>", entry) Next entry Console.Write(vbCrLf & vbCrLf)End Sub'This example produces the following results:'' 1) Split a string delimited by characters:'' The original string is: ",ONE,, TWO,, , THREE,,".' The delimiter character is: ','.'' 1a) Return all elements:' The return value contains these 9 elements:' <><ONE><>< TWO><>< >< THREE><><>'' 1b) Return all elements with whitespace trimmed:' The return value contains these 9 elements:' <><ONE><><TWO><><><THREE><><>'' 1c) Return all non-empty elements:' The return value contains these 4 elements:' <ONE>< TWO>< >< THREE>'' 1d) Return all non-whitespace elements with whitespace trimmed:' The return value contains these 3 elements:' <ONE><TWO><THREE>'' 1e) Split into only two elements:' The return value contains these 2 elements:' <><ONE,, TWO,, , THREE,,>'' 1f) Split into only two elements with whitespace trimmed:' The return value contains these 2 elements:' <><ONE,, TWO,, , THREE,,>'' 1g) Split into only two non-empty elements:' The return value contains these 2 elements:' <ONE>< TWO,, , THREE,,>'' 1h) Split into only two non-whitespace elements with whitespace trimmed:' The return value contains these 2 elements:' <ONE><TWO,, , THREE,,>'' 2) Split a string delimited by another string:'' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".' The delimiter string is: "[stop]".'' 2a) Return all elements:' The return value contains these 9 elements:' <><ONE>< ><TWO ><>< ><THREE><>< >'' 2b) Return all elements with whitespace trimmed:' The return value contains these 9 elements:' <><ONE><><TWO><><><THREE><><>'' 2c) Return all non-empty elements:' The return value contains these 6 elements:' <ONE>< ><TWO >< ><THREE>< >'' 2d) Return all non-whitespace elements with whitespace trimmed:' The return value contains these 3 elements:' <ONE><TWO><THREE>'' 2e) Split into only two elements:' The return value contains these 2 elements:' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >'' 2f) Split into only two elements with whitespace trimmed:' The return value contains these 2 elements:' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>'' 2g) Split into only two non-empty elements:' The return value contains these 2 elements:' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >'' 2h) Split into only two non-whitespace elements with whitespace trimmed:' The return value contains these 2 elements:' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>'

Remarks

Delimiter strings are not included in the elements of the returned array.

If this instance does not contain any of the strings in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

To pass null for the string[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(Char[], Int32, StringSplitOptions). The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick brown fox";_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"phrase.Split(Unchecked.defaultof<string[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split(null :> string[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split((null: string[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"Dim words() As Stringwords = phrase.Split(TryCast(Nothing, String()), 3, StringSplitOptions.RemoveEmptyEntries)words = phrase.Split(New String() {}, 3, StringSplitOptions.RemoveEmptyEntries)

If the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

Each element of separator defines a separate delimiter that consists of one or more characters. If the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

The separator array

If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." returns this four-element array: { "This", "is", "a", "string." }.

Comparison details

The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

The Split method ignores any element of separator whose value is null or the empty string ("").

To avoid ambiguous results when strings in separator have characters in common, the Split method proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

For example, consider an instance whose value is "abcdef". If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be "a" and "f". This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be "a" and "ef". This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be "a" and "def".

Performance considerations

The Split methods allocate memory for the returned array object and a String object for each array element. If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. This significantly reduces the additional overhead of each method call.

Notes to Callers

In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Applies to

Split(Char[], StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Splits a string into substrings based on specified delimiting characters and options.

public: cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, StringSplitOptions options);
public string[] Split (char[] separator, StringSplitOptions options);
public string[] Split (char[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]public string[] Split (char[] separator, StringSplitOptions options);
member this.Split : char[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]member this.Split : char[] * StringSplitOptions -> string[]
Public Function Split (separator As Char(), options As StringSplitOptions) As String()

Parameters

separator
Char[]

An array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Returns

An array whose elements contain the substrings in this string that are delimited by one or more characters in separator. For more information, see the Remarks section.

Attributes

Exceptions

options is not one of the StringSplitOptions values.

Examples

The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// This example demonstrates the String.Split(Char[], Boolean) and // String.Split(Char[], Int32, Boolean) methodsusing namespace System;void Show( array<String^>^entries ){ Console::WriteLine( "The return value contains these {0} elements:", entries->Length ); System::Collections::IEnumerator^ myEnum = entries->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ entry = safe_cast<String^>(myEnum->Current); Console::Write( "<{0}>", entry ); } Console::Write( "{0}{0}", Environment::NewLine );}int main(){ String^ s = ",one,,,two,,,,,three,,"; array<Char>^sep = gcnew array<Char>{ ',' }; array<String^>^result; // Console::WriteLine( "The original string is \"{0}\".", s ); Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] ); Console::WriteLine(); // Console::WriteLine( "Split the string and return all elements:" ); result = s->Split( sep, StringSplitOptions::None ); Show( result ); // Console::WriteLine( "Split the string and return all non-empty elements:" ); result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries ); Show( result ); // Console::WriteLine( "Split the string and return 2 elements:" ); result = s->Split( sep, 2, StringSplitOptions::None ); Show( result ); // Console::WriteLine( "Split the string and return 2 non-empty elements:" ); result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries ); Show( result );}/*This example produces the following results:The original string is ",one,,,two,,,,,three,,".The separation character is ','.Split the string and return all elements:The return value contains these 12 elements:<><one><><><two><><><><><three><><>Split the string and return all non-empty elements:The return value contains these 3 elements:<one><two><three>Split the string and return 2 elements:The return value contains these 2 elements:<><one,,,two,,,,,three,,>Split the string and return 2 non-empty elements:The return value contains these 2 elements:<one><,,two,,,,,three,,>*/
// This example demonstrates the String.Split() methods that use// the StringSplitOptions enumeration.// Example 1: Split a string delimited by charactersConsole.WriteLine("1) Split a string delimited by characters:\n");string s1 = ",ONE,, TWO,, , THREE,,";char[] charSeparators = new char[] { ',' };string[] result;Console.WriteLine($"The original string is: \"{s1}\".");Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");// Split the string and return all elementsConsole.WriteLine("1a) Return all elements:");result = s1.Split(charSeparators, StringSplitOptions.None);Show(result);// Split the string and return all elements with whitespace trimmedConsole.WriteLine("1b) Return all elements with whitespace trimmed:");result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);Show(result);// Split the string and return all non-empty elementsConsole.WriteLine("1c) Return all non-empty elements:");result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string and return all non-whitespace elements with whitespace trimmedConsole.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Split the string into only two elements, keeping the remainder in the last matchConsole.WriteLine("1e) Split into only two elements:");result = s1.Split(charSeparators, 2, StringSplitOptions.None);Show(result);// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("1f) Split into only two elements with whitespace trimmed:");result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);Show(result);// Split the string into only two non-empty elements, keeping the remainder in the last matchConsole.WriteLine("1g) Split into only two non-empty elements:");result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Example 2: Split a string delimited by another stringConsole.WriteLine("2) Split a string delimited by another string:\n");string s2 = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] ";string[] stringSeparators = new string[] { "[stop]" };Console.WriteLine($"The original string is: \"{s2}\".");Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");// Split the string and return all elementsConsole.WriteLine("2a) Return all elements:");result = s2.Split(stringSeparators, StringSplitOptions.None);Show(result);// Split the string and return all elements with whitespace trimmedConsole.WriteLine("2b) Return all elements with whitespace trimmed:");result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);Show(result);// Split the string and return all non-empty elementsConsole.WriteLine("2c) Return all non-empty elements:");result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string and return all non-whitespace elements with whitespace trimmedConsole.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Split the string into only two elements, keeping the remainder in the last matchConsole.WriteLine("2e) Split into only two elements:");result = s2.Split(stringSeparators, 2, StringSplitOptions.None);Show(result);// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("2f) Split into only two elements with whitespace trimmed:");result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);Show(result);// Split the string into only two non-empty elements, keeping the remainder in the last matchConsole.WriteLine("2g) Split into only two non-empty elements:");result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);Show(result);// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchConsole.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);Show(result);// Display the array of separated strings using a local functionvoid Show(string[] entries){ Console.WriteLine($"The return value contains these {entries.Length} elements:"); foreach (string entry in entries) { Console.Write($"<{entry}>"); } Console.Write("\n\n");}/*This example produces the following results:1) Split a string delimited by characters:The original string is: ",ONE,, TWO,, , THREE,,".The delimiter character is: ','.1a) Return all elements:The return value contains these 9 elements:<><ONE><>< TWO><>< >< THREE><><>1b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>1c) Return all non-empty elements:The return value contains these 4 elements:<ONE>< TWO>< >< THREE>1d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>1e) Split into only two elements:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< TWO,, , THREE,,>1h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO,, , THREE,,>2) Split a string delimited by another string:The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".The delimiter string is: "[stop]".2a) Return all elements:The return value contains these 9 elements:<><ONE>< ><TWO ><>< ><THREE><>< >2b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>2c) Return all non-empty elements:The return value contains these 6 elements:<ONE>< ><TWO >< ><THREE>< >2d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>2e) Split into only two elements:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>2g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>*/
// This example demonstrates the String.Split() methods that use// the StringSplitOptions enumeration.// Display the array of separated strings using a local functionlet show (entries: string[]) = printfn $"The return value contains these {entries.Length} elements:" for entry in entries do printf $"<{entry}>" printf "\n\n"// Example 1: Split a string delimited by charactersprintfn "1) Split a string delimited by characters:\n"let s1 = ",ONE,, TWO,, , THREE,,"let charSeparators = [| ',' |]printfn $"The original string is: \"{s1}\"."printfn $"The delimiter character is: '{charSeparators[0]}'.\n"// Split the string and return all elementsprintfn "1a) Return all elements:"let result = s1.Split(charSeparators, StringSplitOptions.None)show result// Split the string and return all elements with whitespace trimmedprintfn "1b) Return all elements with whitespace trimmed:"let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)show result// Split the string and return all non-empty elementsprintfn "1c) Return all non-empty elements:"let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)show result// Split the string and return all non-whitespace elements with whitespace trimmedprintfn "1d) Return all non-whitespace elements with whitespace trimmed:"let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Split the string into only two elements, keeping the remainder in the last matchprintfn "1e) Split into only two elements:"let result = s1.Split(charSeparators, 2, StringSplitOptions.None)show result// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchprintfn "1f) Split into only two elements with whitespace trimmed:"let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)show result// Split the string into only two non-empty elements, keeping the remainder in the last matchprintfn "1g) Split into only two non-empty elements:"let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)show result// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchprintfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Example 2: Split a string delimited by another stringprintfn "2) Split a string delimited by another string:\n"let s2 = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] "let stringSeparators = [| "[stop]" |]printfn $"The original string is: \"{s2}\"."printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"// Split the string and return all elementsprintfn "2a) Return all elements:"let result = s2.Split(stringSeparators, StringSplitOptions.None)show result// Split the string and return all elements with whitespace trimmedprintfn "2b) Return all elements with whitespace trimmed:"let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)show result// Split the string and return all non-empty elementsprintfn "2c) Return all non-empty elements:"let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)show result// Split the string and return all non-whitespace elements with whitespace trimmedprintfn "2d) Return all non-whitespace elements with whitespace trimmed:"let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result// Split the string into only two elements, keeping the remainder in the last matchprintfn "2e) Split into only two elements:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)show result// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last matchprintfn "2f) Split into only two elements with whitespace trimmed:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)show result// Split the string into only two non-empty elements, keeping the remainder in the last matchprintfn "2g) Split into only two non-empty elements:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)show result// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last matchprintfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)show result(*This example produces the following results:1) Split a string delimited by characters:The original string is: ",ONE,, TWO,, , THREE,,".The delimiter character is: ','.1a) Return all elements:The return value contains these 9 elements:<><ONE><>< TWO><>< >< THREE><><>1b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>1c) Return all non-empty elements:The return value contains these 4 elements:<ONE>< TWO>< >< THREE>1d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>1e) Split into only two elements:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE,, TWO,, , THREE,,>1g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< TWO,, , THREE,,>1h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO,, , THREE,,>2) Split a string delimited by another string:The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".The delimiter string is: "[stop]".2a) Return all elements:The return value contains these 9 elements:<><ONE>< ><TWO ><>< ><THREE><>< >2b) Return all elements with whitespace trimmed:The return value contains these 9 elements:<><ONE><><TWO><><><THREE><><>2c) Return all non-empty elements:The return value contains these 6 elements:<ONE>< ><TWO >< ><THREE>< >2d) Return all non-whitespace elements with whitespace trimmed:The return value contains these 3 elements:<ONE><TWO><THREE>2e) Split into only two elements:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2f) Split into only two elements with whitespace trimmed:The return value contains these 2 elements:<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>2g) Split into only two non-empty elements:The return value contains these 2 elements:<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >2h) Split into only two non-whitespace elements with whitespace trimmed:The return value contains these 2 elements:<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>*)
Public Shared Sub StringSplitOptionsExamples() ' This example demonstrates the String.Split() methods that use ' the StringSplitOptions enumeration. ' Example 1: Split a string delimited by characters Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf) Dim s1 As String = ",ONE,, TWO,, , THREE,," Dim charSeparators() As Char = {","c} Dim result() As String Console.WriteLine("The original string is: ""{0}"".", s1) Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0)) ' Split the string and return all elements Console.WriteLine("1a) Return all elements:") result = s1.Split(charSeparators, StringSplitOptions.None) Show(result) ' Split the string and return all elements with whitespace trimmed Console.WriteLine("1b) Return all elements with whitespace trimmed:") result = s1.Split(charSeparators, StringSplitOptions.TrimEntries) Show(result) ' Split the string and return all non-empty elements Console.WriteLine("1c) Return all non-empty elements:") result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string and return all non-whitespace elements with whitespace trimmed Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:") result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two elements, keeping the remainder in the last match Console.WriteLine("1e) Split into only two elements:") result = s1.Split(charSeparators, 2, StringSplitOptions.None) Show(result) ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("1f) Split into only two elements with whitespace trimmed:") result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two non-empty elements, keeping the remainder in the last match Console.WriteLine("1g) Split into only two non-empty elements:") result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:") result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Example 2: Split a string delimited by another string Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf) Dim s2 As String = "[stop]" + "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] " Dim stringSeparators() As String = {"[stop]"} Console.WriteLine("The original string is: ""{0}"".", s2) Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0)) ' Split the string and return all elements Console.WriteLine("2a) Return all elements:") result = s2.Split(stringSeparators, StringSplitOptions.None) Show(result) ' Split the string and return all elements with whitespace trimmed Console.WriteLine("2b) Return all elements with whitespace trimmed:") result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries) Show(result) ' Split the string and return all non-empty elements Console.WriteLine("2c) Return all non-empty elements:") result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string and return all non-whitespace elements with whitespace trimmed Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:") result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two elements, keeping the remainder in the last match Console.WriteLine("2e) Split into only two elements:") result = s2.Split(stringSeparators, 2, StringSplitOptions.None) Show(result) ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("2f) Split into only two elements with whitespace trimmed:") result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries) Show(result) ' Split the string into only two non-empty elements, keeping the remainder in the last match Console.WriteLine("2g) Split into only two non-empty elements:") result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries) Show(result) ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:") result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) Show(result)End Sub' Display the array of separated strings.Public Shared Sub Show(ByVal entries() As String) Console.WriteLine("The return value contains these {0} elements:", entries.Length) Dim entry As String For Each entry In entries Console.Write("<{0}>", entry) Next entry Console.Write(vbCrLf & vbCrLf)End Sub'This example produces the following results:'' 1) Split a string delimited by characters:'' The original string is: ",ONE,, TWO,, , THREE,,".' The delimiter character is: ','.'' 1a) Return all elements:' The return value contains these 9 elements:' <><ONE><>< TWO><>< >< THREE><><>'' 1b) Return all elements with whitespace trimmed:' The return value contains these 9 elements:' <><ONE><><TWO><><><THREE><><>'' 1c) Return all non-empty elements:' The return value contains these 4 elements:' <ONE>< TWO>< >< THREE>'' 1d) Return all non-whitespace elements with whitespace trimmed:' The return value contains these 3 elements:' <ONE><TWO><THREE>'' 1e) Split into only two elements:' The return value contains these 2 elements:' <><ONE,, TWO,, , THREE,,>'' 1f) Split into only two elements with whitespace trimmed:' The return value contains these 2 elements:' <><ONE,, TWO,, , THREE,,>'' 1g) Split into only two non-empty elements:' The return value contains these 2 elements:' <ONE>< TWO,, , THREE,,>'' 1h) Split into only two non-whitespace elements with whitespace trimmed:' The return value contains these 2 elements:' <ONE><TWO,, , THREE,,>'' 2) Split a string delimited by another string:'' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".' The delimiter string is: "[stop]".'' 2a) Return all elements:' The return value contains these 9 elements:' <><ONE>< ><TWO ><>< ><THREE><>< >'' 2b) Return all elements with whitespace trimmed:' The return value contains these 9 elements:' <><ONE><><TWO><><><THREE><><>'' 2c) Return all non-empty elements:' The return value contains these 6 elements:' <ONE>< ><TWO >< ><THREE>< >'' 2d) Return all non-whitespace elements with whitespace trimmed:' The return value contains these 3 elements:' <ONE><TWO><THREE>'' 2e) Split into only two elements:' The return value contains these 2 elements:' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >'' 2f) Split into only two elements with whitespace trimmed:' The return value contains these 2 elements:' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>'' 2g) Split into only two non-empty elements:' The return value contains these 2 elements:' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >'' 2h) Split into only two non-whitespace elements with whitespace trimmed:' The return value contains these 2 elements:' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>'

Remarks

Delimiter characters (the characters in the separator array) are not included in the elements of the returned array. For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

If the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

Each element of separator defines a separate delimiter that consists of a single character. If the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. For example, if separator includes two elements, '-' and '_', the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty, which represents the empty string that precedes the "-" character at index 0.

  2. String.Empty, which represents the empty string between the "-" character at index 0 and the "_" character at index 1.

  3. "aa".

  4. String.Empty, which represents the empty string that follows the "-" character at index 4.

  5. String.Empty, which represents the empty string that follows the "_" character at index 5.

The separator array

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

To pass null for the char[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(String[], StringSplitOptions). The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick brown fox";_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"phrase.Split(Unchecked.defaultof<char[]>, StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split(null :> char[], StringSplitOptions.RemoveEmptyEntries) |> ignorephrase.Split((null: char[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"Dim words() As Stringwords = phrase.Split(TryCast(Nothing, Char()), StringSplitOptions.RemoveEmptyEntries)words = phrase.Split(New Char() {}, StringSplitOptions.RemoveEmptyEntries)

Comparison details

The Split method extracts the substrings in this string that are delimited by one or more of the characters in the separator parameter, and returns those substrings as elements of an array.

The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

Performance considerations

The Split methods allocate memory for the returned array object and a String object for each array element. If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. This significantly reduces the additional overhead of each method call.

Notes to Callers

In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Applies to

String.Split Method (System) (2024)

FAQs

What is the string split method? ›

The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

What is string split () Roblox? ›

split. table. Splits a string into parts based on the defined separator character(s), returning a table of ordered results. If an empty "slice" is located, that part will be returned as an empty string.

What does the Python split method do for strings? ›

The split() method converts the string into other data types like lists by breaking a string into pieces. Python provides us with two methods: . split() and . rsplit() .

What is the string split method in C#? ›

The String. Split method creates an array of substrings by splitting the input string based on one or more delimiters. This method is often the easiest way to separate a string on word boundaries. It's also used to split strings on other specific characters or strings.

How do you split a string variable? ›

split splits the contents of a string variable, strvar, into one or more parts, using one or more parse strings (by default, blank spaces), so that new string variables are generated. Thus split is useful for separating “words” or other parts of a string variable. strvar itself is not modified.

What is the difference between split () and slicing in Python? ›

In essence: - `split()` divides a string into smaller parts based on a character or pattern. - Slicing extracts a portion of a string directly by specifying the start and end positions.

How do you split and remove a string in Python? ›

3 Methods to Trim a String in Python
  1. strip() : Removes leading and trailing characters (whitespace by default).
  2. lstrip() : Removes leading characters (whitespace by default) from the left side of the string.
  3. rstrip() : Removes trailing characters (whitespace by default) from the right side of the string.

What is the difference between string split and strip in Python? ›

Strip() and split() are different Python built-in methods performed on strings. The strip() method in Python is used to remove the whitespace or the characters that are passed in the argument. The split() method, on the other hand, is used to split the string into substrings.

How to split a string in C programming? ›

The strtok() function is a library function in the C programming language that breaks a given string into a series of tokens using a specified delimiter. This function is declared in the string. h header file and is commonly used for text parsing and manipulation operations.

What is string split vs slice? ›

Split() method is used for strings array, slice() method is used for both arrays and strings. Splice() method is used for only arrays. If you want to read more blog, you can check out my personal page.

How to use string split in SQL? ›

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and the space ( ' ' ) as the second argument.

What is the splitting method? ›

Splitting methods constitute a general class of numerical integration schemes for dif- ferential equations whose vector field can be decomposed in such a way that each. sub-problem is simpler to integrate than the original system.

What is the split method in regex? ›

Split(String, String, RegexOptions, TimeSpan) Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

What is the string split method in Golang? ›

The method split() in the Golang Split String is defined as a string library that breaks the string into a list of substrings by using a specified separator. The split() method returns the output of the substring in the form of the slice.

Top Articles
How to Configure VLANs on OPNsense? - zenarmor.com
Is it necessary to log in with my Ubisoft account to play Just Dance Now? — Just Dance Now Help Center
Duralast Gold Cv Axle
Soap2Day Autoplay
Professor Qwertyson
Jennette Mccurdy And Joe Tmz Photos
Samsung 9C8
Jesus Revolution Showtimes Near Chisholm Trail 8
Employeeres Ual
A Fashion Lover's Guide To Copenhagen
Www.paystubportal.com/7-11 Login
Planets Visible Tonight Virginia
Raid Guides - Hardstuck
Ts Lillydoll
Uc Santa Cruz Events
DoorDash, Inc. (DASH) Stock Price, Quote & News - Stock Analysis
Bcbs Prefix List Phone Numbers
Lonesome Valley Barber
Satisfactory: How to Make Efficient Factories (Tips, Tricks, & Strategies)
Soulstone Survivors Igg
Certain Red Dye Nyt Crossword
C&T Wok Menu - Morrisville, NC Restaurant
Red8 Data Entry Job
Bill Remini Obituary
Lines Ac And Rs Can Best Be Described As
California Online Traffic School
Pain Out Maxx Kratom
Urbfsdreamgirl
2023 Ford Bronco Raptor for sale - Dallas, TX - craigslist
Combies Overlijden no. 02, Stempels: 2 teksten + 1 tag/label & Stansen: 3 tags/labels.
Pokemon Inflamed Red Cheats
Amazing Lash Bay Colony
Elanco Rebates.com 2022
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Forager How-to Get Archaeology Items - Dino Egg, Anchor, Fossil, Frozen Relic, Frozen Squid, Kapala, Lava Eel, and More!
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
Bus Dublin : guide complet, tarifs et infos pratiques en 2024 !
T&J Agnes Theaters
Gwu Apps
Bay Focus
Page 5662 – Christianity Today
Koninklijk Theater Tuschinski
Shuaiby Kill Twitter
Birmingham City Schools Clever Login
Www Craigslist Com Atlanta Ga
St Vrain Schoology
Bonecrusher Upgrade Rs3
Craigslist Pets Charleston Wv
4Chan Zelda Totk
Bismarck Mandan Mugshots
Hsi Delphi Forum
Gameplay Clarkston
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6622

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.