String.Split Méthode

Définition

Retourne un tableau de chaînes qui contient les sous-chaînes de cette instance, séparées par les éléments d'une chaîne ou d'un tableau de caractères Unicode spécifiés.

Surcharges

Split(Char[])

Divise une chaîne en sous-chaînes en fonction de caractères de délimitation spécifiés.

Split(Char, StringSplitOptions)

Divise une chaîne en sous-chaînes en fonction d’un caractère de délimitation spécifié et, éventuellement, d’options.

Split(Char[], Int32)

Divise une chaîne en un nombre maximal de sous-chaînes en fonction de caractères de délimitation spécifiés.

Split(Char[], StringSplitOptions)

Divise une chaîne en sous-chaînes en fonction de caractères de délimitation spécifiés et d’options.

Split(String, StringSplitOptions)

Divise une chaîne en sous-chaînes d’après le séparateur de chaînes fourni.

Split(String[], StringSplitOptions)

Divise une chaîne en sous-chaînes en fonction d’une chaîne de délimitation spécifiée et, éventuellement, d’options.

Split(Char, Int32, StringSplitOptions)

Divise une chaîne en un nombre maximal de sous-chaînes en fonction d’un caractère de délimitation spécifié et, éventuellement, d’options. Divise une chaîne en un nombre maximal de sous-chaînes en fonction du séparateur de caractères fourni, en omettant éventuellement les sous-chaînes vides du résultat.

Split(Char[], Int32, StringSplitOptions)

Divise une chaîne en un nombre maximal de sous-chaînes en fonction de caractères de délimitation spécifiés et, éventuellement, d’options.

Split(String, Int32, StringSplitOptions)

Divise une chaîne en un nombre maximal de sous-chaînes en fonction d’une chaîne de délimitation spécifiée et, éventuellement, d’options.

Split(String[], Int32, StringSplitOptions)

Divise une chaîne en un nombre maximal de sous-chaînes en fonction de chaînes de délimitation spécifiées et, éventuellement, d’options.

Remarques

Split est utilisé pour diviser une chaîne délimitée en sous-chaînes. Vous pouvez utiliser un tableau de caractères ou un tableau de chaînes pour spécifier zéro ou plusieurs caractères ou chaînes de délimitation. Si aucun caractère de délimitation n’est spécifié, la chaîne est fractionnée à des espaces blancs.

Les surcharges de la Split méthode vous permettent de limiter le nombre de sous-chaînes retournées par la méthode (la Split(Char[], Int32) méthode), de spécifier s’il faut inclure des chaînes vides et/ou réduire les sous-chaînes dans le résultat (les Split(Char[], StringSplitOptions) méthodes et Split(String[], StringSplitOptions) ), ou d’effectuer les deux (méthodes Split(Char[], Int32, StringSplitOptions) et Split(String[], Int32, StringSplitOptions) ).

Conseil

La Split méthode n’est pas toujours la meilleure façon de diviser une chaîne délimitée en sous-chaînes. Si vous ne souhaitez pas extraire toutes les sous-chaînes d’une chaîne délimitée, ou si vous souhaitez analyser une chaîne basée sur un modèle au lieu d’un ensemble de caractères délimiteurs, envisagez d’utiliser des expressions régulières ou de combiner l’une des méthodes de recherche qui retourne l’index d’un caractère avec la Substring méthode . Pour plus d’informations, consultez Extraire des sous-chaînes à partir d’une chaîne.

 Exemple

Les exemples suivants montrent trois surcharges différentes de String.Split(). Le premier exemple appelle la Split(Char[]) surcharge et passe un délimiteur unique.

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.

Comme vous pouvez le voir, les caractères de point (.) sont inclus dans deux des sous-chaînes. Si vous souhaitez exclure les caractères de point, vous pouvez ajouter le caractère de point en tant que caractère délimitant supplémentaire. L’exemple suivant montre comment procéder.

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:

Les points sont exclus des sous-chaînes, mais maintenant deux sous-chaînes vides supplémentaires ont été incluses. Ces sous-chaînes vides représentent la sous-chaîne entre un mot et le point qui le suit. Pour omettre les sous-chaînes vides du tableau résultant, vous pouvez appeler la surcharge Split(Char[], StringSplitOptions) et spécifier StringSplitOptions.RemoveEmptyEntries pour le paramètre options.

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

Les sections pour les surcharges individuelles de contiennent d’autres String.Split() exemples.

Split(Char[])

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

Divise une chaîne en sous-chaînes en fonction de caractères de délimitation spécifiés.

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()

Paramètres

separator
Char[]

Tableau de caractères de délimitation, tableau vide qui ne contient pas de délimiteurs ni de null.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette instance qui sont délimitées par un ou plusieurs caractères dans separator. Pour plus d'informations, consultez la section Remarques.

Exemples

L’exemple suivant montre comment extraire des mots individuels d’un bloc de texte en traitant le caractère d’espace ( ) et le caractère de tabulation (\t) comme des délimiteurs. La chaîne en cours de fractionnement comprend ces deux caractères.

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

Remarques

Lorsqu’une chaîne est délimitée par un ensemble de caractères connu, vous pouvez utiliser la méthode pour la Split(Char[]) séparer en sous-chaînes.

Les caractères délimiteurs ne sont pas inclus dans les éléments du tableau retourné. Par exemple, si le tableau de séparation inclut le caractère « - » et que la valeur de la chaîne actuelle instance est « aa-bb-cc », la méthode retourne un tableau qui contient trois éléments : « aa », « bb » et « cc ».

Si cette instance ne contient aucun des caractères dans separator, le tableau retourné se compose d’un seul élément qui contient ce instance.

Chaque élément de separator définit un caractère délimiteur distinct. Si deux délimiteurs sont adjacents, ou si un délimiteur est trouvé au début ou à la fin de cette instance, l’élément correspondant dans le tableau retourné contient Empty.

Le tableau suivant montre quelques exemples.

Langage Valeur de chaîne Séparateur Tableau retourné
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 » Rien {"Darb », « Smarba"}

Tableau de séparateurs

Chaque élément de séparateur définit un délimiteur distinct qui se compose d’un caractère unique.

Si l’argument separator est null ou ne contient aucun caractère, la méthode traite les espaces blancs comme les délimiteurs. Les espaces blancs sont définis par la norme Unicode, et la Char.IsWhiteSpace méthode retourne true si un espace blanc lui est transmis.

Résolution de surcharge string.Split(Char[]) et du compilateur

Bien que le paramètre unique de cette surcharge de soit un tableau de String.Split caractères, vous pouvez l’appeler avec un seul caractère, comme le montre l’exemple suivant.

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 delimiter
for 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)
    Next
End Sub

' The example displays the following output:
'
'     Thi
'      i
'      a
'     hort
'     tring.

Étant donné que le separator paramètre est décoré avec l’attribut ParamArrayAttribute , les compilateurs interprètent un caractère unique comme un tableau de caractères à élément unique. Ce n’est pas le cas pour les autres String.Split surcharges qui incluent un separator paramètre ; vous devez passer explicitement ces surcharges un tableau de caractères en tant qu’argument separator .

Détails de la comparaison

La Split(Char[]) méthode extrait les sous-chaînes de cette chaîne qui sont délimitées par un ou plusieurs caractères du separator tableau et retourne ces sous-chaînes en tant qu’éléments d’un tableau.

La Split(Char[]) méthode recherche des délimiteurs en effectuant des comparaisons à l’aide de règles de tri ordinale respectant la casse. Pour plus d’informations sur les tris de mots, de chaînes et ordinaux, consultez l’énumération System.Globalization.CompareOptions .

Considérations relatives aux performances

Les Split méthodes allouent de la mémoire pour l’objet tableau retourné et un String objet pour chaque élément de tableau. Si votre application nécessite des performances optimales ou si la gestion de l’allocation de mémoire est essentielle dans votre application, envisagez d’utiliser la IndexOf méthode ou IndexOfAny . Vous avez également la possibilité d’utiliser la Compare méthode pour localiser une sous-chaîne dans une chaîne.

Pour fractionner une chaîne au niveau d’un caractère séparateur, utilisez la IndexOf méthode ou IndexOfAny pour localiser un caractère de séparateur dans la chaîne. Pour fractionner une chaîne au niveau d’une chaîne de séparation, utilisez la IndexOf méthode ou IndexOfAny pour localiser le premier caractère de la chaîne de séparation. Utilisez ensuite la Compare méthode pour déterminer si les caractères qui suivent ce premier caractère sont égaux aux caractères restants de la chaîne de séparation.

En outre, si le même ensemble de caractères est utilisé pour fractionner des chaînes dans plusieurs Split appels de méthode, envisagez de créer un tableau unique et de le référencer dans chaque appel de méthode. Cela réduit considérablement la surcharge supplémentaire de chaque appel de méthode.

Notes pour les appelants

Dans .NET Framework 3.5 et versions antérieures, si la Split(Char[]) méthode est passée à un separator qui est null ou ne contient pas de caractères, la méthode utilise un jeu d’espaces blancs légèrement différent pour fractionner la chaîne que la Trim(Char[]) méthode pour découper la chaîne. À compter de .NET Framework 4, les deux méthodes utilisent un jeu identique de caractères d’espace blanc Unicode.

Voir aussi

S’applique à

Split(Char, StringSplitOptions)

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

Divise une chaîne en sous-chaînes en fonction d’un caractère de délimitation spécifié et, éventuellement, d’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()

Paramètres

separator
Char

Caractère qui délimite les sous-chaînes de cette chaîne.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette instance, qui sont délimitées par separator.

S’applique à

Split(Char[], Int32)

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

Divise une chaîne en un nombre maximal de sous-chaînes en fonction de caractères de délimitation spécifiés.

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()

Paramètres

separator
Char[]

Tableau de caractères qui délimitent les sous-chaînes de cette chaîne, tableau vide qui ne contient pas de délimiteur ni de null.

count
Int32

Nombre maximal de sous-chaînes à retourner.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette instance qui sont délimitées par un ou plusieurs caractères dans separator. Pour plus d'informations, consultez la section Remarques.

Exceptions

count est un nombre négatif.

Exemples

L’exemple suivant montre comment count peut être utilisé pour limiter le nombre de chaînes retournées par 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(Nothing, 2)
Dim firstName As String = substrings(0)
Dim lastName As String

If substrings.Length > 1 Then
    lastName = substrings(1)
End If

' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"

Remarques

Les caractères délimiteurs ne sont pas inclus dans les éléments du tableau retourné.

Si cette instance ne contient aucun des caractères dans separator, le tableau retourné se compose d’un seul élément qui contient ce instance. Si count est zéro, un tableau vide est retourné.

Si le separator paramètre est null ou ne contient aucun caractère, les espaces blancs sont supposés être les délimiteurs. Les espaces blancs sont définis par la norme Unicode et la Char.IsWhiteSpace méthode retourne true s’ils lui sont passés.

Chaque élément de separator définit un caractère délimiteur distinct. Si deux délimiteurs sont adjacents, ou si un délimiteur est trouvé au début ou à la fin de cette instance, l’élément de tableau correspondant contient Empty.

Si cette instance contient plus de count sous-chaînes, les premières count - 1 sous-chaînes sont retournées dans les premiers count - 1 éléments de la valeur de retour, et les caractères restants dans cette instance sont retournés dans le dernier élément de la valeur de retour.

Si count est supérieur au nombre de sous-chaînes, les sous-chaînes disponibles sont retournées et aucune exception n’est levée.

Le tableau suivant montre quelques exemples.

Langage Valeur de chaîne Séparateur Tableau retourné
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 » Rien {"Darb », « Smarba"}

Considérations relatives aux performances

Les Split méthodes allouent de la mémoire pour l’objet tableau retourné et un String objet pour chaque élément de tableau. Si votre application nécessite des performances optimales ou si la gestion de l’allocation de mémoire est essentielle dans votre application, envisagez d’utiliser la IndexOf méthode ou IndexOfAny et éventuellement la Compare méthode pour localiser une sous-chaîne dans une chaîne.

Si vous fractionnement une chaîne au niveau d’un caractère séparateur, utilisez la IndexOf méthode ou IndexOfAny pour localiser un caractère de séparateur dans la chaîne. Si vous fractionnement une chaîne au niveau d’une chaîne de séparation, utilisez la IndexOf méthode ou IndexOfAny pour localiser le premier caractère de la chaîne de séparation. Utilisez ensuite la Compare méthode pour déterminer si les caractères qui suivent ce premier caractère sont égaux aux caractères restants de la chaîne de séparation.

En outre, si le même ensemble de caractères est utilisé pour fractionner des chaînes dans plusieurs Split appels de méthode, envisagez de créer un tableau unique et de le référencer dans chaque appel de méthode. Cela réduit considérablement la surcharge supplémentaire de chaque appel de méthode.

Notes pour les appelants

Dans .NET Framework 3.5 et versions antérieures, si la Split(Char[]) méthode est passée à un separator qui est null ou ne contient pas de caractères, la méthode utilise un jeu d’espaces blancs légèrement différent pour fractionner la chaîne que la Trim(Char[]) méthode pour découper la chaîne. À compter de .NET Framework 4, les deux méthodes utilisent un jeu identique de caractères d’espace blanc Unicode.

Voir aussi

S’applique à

Split(Char[], StringSplitOptions)

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

Divise une chaîne en sous-chaînes en fonction de caractères de délimitation spécifiés et d’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()

Paramètres

separator
Char[]

Tableau de caractères qui délimitent les sous-chaînes de cette chaîne, tableau vide qui ne contient pas de délimiteur ni de null.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette chaîne qui sont délimitées par un ou plusieurs caractères dans separator. Pour plus d'informations, consultez la section Remarques.

Attributs

Exceptions

options ne fait pas partie des valeurs StringSplitOptions.

Exemples

L’exemple suivant utilise l’énumération StringSplitOptions pour inclure ou exclure les sous-chaînes générées par la Split méthode .

// This example demonstrates the String.Split(Char[], Boolean) and 
//                               String.Split(Char[], Int32, Boolean) methods
using 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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void 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:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
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 function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    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:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

Remarques

Les caractères délimiteurs (les caractères du separator tableau) ne sont pas inclus dans les éléments du tableau retourné. Par exemple, si le separator tableau inclut le caractère « - » et que la valeur de la chaîne actuelle instance est « aa-bb-cc », la méthode retourne un tableau qui contient trois éléments : « aa », « bb » et « cc ».

Si cette instance ne contient aucun des caractères dans separator, le tableau retourné se compose d’un seul élément qui contient ce instance.

Si le options paramètre est RemoveEmptyEntries et que la longueur de ce instance est égale à zéro, la méthode retourne un tableau vide.

Chaque élément de separator définit un délimiteur distinct qui se compose d’un caractère unique. Si l’argument options est Noneet que deux délimiteurs sont adjacents ou si un délimiteur est trouvé au début ou à la fin de cette instance, l’élément de tableau correspondant contient String.Empty. Par exemple, si separator inclut deux éléments, '-' et '_', la valeur de la chaîne instance est « -_aa-_ », et la valeur de l’argument options est None, la méthode retourne un tableau de chaînes avec les cinq éléments suivants :

  1. String.Empty, qui représente la chaîne vide qui précède le caractère « - » à l’index 0.

  2. String.Empty, qui représente la chaîne vide entre le caractère « - » à l’index 0 et le caractère « _ » à l’index 1.

  3. « aa ».

  4. String.Empty, qui représente la chaîne vide qui suit le caractère « - » à l’index 4.

  5. String.Empty, qui représente la chaîne vide qui suit le caractère « _ » à l’index 5.

Tableau de séparateurs

Si le separator paramètre est null ou ne contient aucun caractère, les espaces blancs sont supposés être les délimiteurs. Les espaces blancs sont définis par la norme Unicode et la Char.IsWhiteSpace méthode retourne true s’ils lui sont passés.

Pour passer null pour le char[] separator paramètre, vous devez indiquer le type de pour null lever l’ambiguïté de l’appel à partir d’autres surcharges, telles que Split(String[], StringSplitOptions). L’exemple suivant montre plusieurs façons d’identifier sans ambiguïté cette surcharge.

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) |> ignore

phrase.Split(null :> char[], StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: char[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, Char()),
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New Char() {},
                     StringSplitOptions.RemoveEmptyEntries)

Détails de la comparaison

La Split méthode extrait les sous-chaînes de cette chaîne délimitées par un ou plusieurs caractères du separator paramètre et retourne ces sous-chaînes en tant qu’éléments d’un tableau.

La Split méthode recherche des délimiteurs en effectuant des comparaisons à l’aide de règles de tri ordinale respectant la casse. Pour plus d’informations sur les tris de mots, de chaînes et ordinaux, consultez l’énumération System.Globalization.CompareOptions .

Considérations relatives aux performances

Les Split méthodes allouent de la mémoire pour l’objet tableau retourné et un String objet pour chaque élément de tableau. Si votre application nécessite des performances optimales ou si la gestion de l’allocation de mémoire est essentielle dans votre application, envisagez d’utiliser la IndexOf méthode ou IndexOfAny et éventuellement la Compare méthode pour localiser une sous-chaîne dans une chaîne.

Si vous fractionnement une chaîne au niveau d’un caractère séparateur, utilisez la IndexOf méthode ou IndexOfAny pour localiser un caractère de séparateur dans la chaîne. Si vous fractionnement une chaîne au niveau d’une chaîne de séparation, utilisez la IndexOf méthode ou IndexOfAny pour localiser le premier caractère de la chaîne de séparation. Utilisez ensuite la Compare méthode pour déterminer si les caractères qui suivent ce premier caractère sont égaux aux caractères restants de la chaîne de séparation.

En outre, si le même ensemble de caractères est utilisé pour fractionner des chaînes dans plusieurs Split appels de méthode, envisagez de créer un tableau unique et de le référencer dans chaque appel de méthode. Cela réduit considérablement la surcharge supplémentaire de chaque appel de méthode.

Notes pour les appelants

Dans .NET Framework 3.5 et versions antérieures, si la Split(Char[]) méthode est passée à un separator qui est null ou ne contient pas de caractères, la méthode utilise un jeu d’espaces blancs légèrement différent pour fractionner la chaîne que la Trim(Char[]) méthode pour découper la chaîne. À compter de .NET Framework 4, les deux méthodes utilisent un jeu identique de caractères d’espace blanc Unicode.

S’applique à

Split(String, StringSplitOptions)

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

Divise une chaîne en sous-chaînes d’après le séparateur de chaînes fourni.

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()

Paramètres

separator
String

Chaîne qui délimite les sous-chaînes de cette chaîne.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette instance, qui sont délimitées par separator.

S’applique à

Split(String[], StringSplitOptions)

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

Divise une chaîne en sous-chaînes en fonction d’une chaîne de délimitation spécifiée et, éventuellement, d’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()

Paramètres

separator
String[]

Tableau de chaînes qui délimitent les sous-chaînes de cette chaîne, tableau vide qui ne contient pas de délimiteur ni de null.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette chaîne qui sont délimitées par une ou plusieurs chaînes dans separator. Pour plus d'informations, consultez la section Remarques.

Attributs

Exceptions

options ne fait pas partie des valeurs StringSplitOptions.

Exemples

L’exemple suivant illustre la différence dans les tableaux retournés en appelant la méthode d’une String.Split(String[], StringSplitOptions) chaîne avec son options paramètre égal à StringSplitOptions.None et 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))
Next
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 ({0} elements):",
                result.Length)
Console.Write("   ")
For Each s As String In result
    Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
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'

L’exemple suivant définit un tableau de séparateurs qui incluent des caractères de ponctuation et d’espace blanc. Le passage de ce tableau avec une valeur à StringSplitOptions.RemoveEmptyEntries la Split(String[], StringSplitOptions) méthode retourne un tableau qui se compose des mots individuels de la chaîne.

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)
    Next
End Sub

' The example displays the following output:
'
'       The
'       handsome
'       energetic
'       young
'       dog
'       was
'       playing
'       with
'       his
'       smaller
'       more
'       lethargic
'       litter
'       mate

Notez que la méthode est appelée avec l’argument options défini sur StringSplitOptions.RemoveEmptyEntries. Cela empêche le tableau retourné d’inclure des String.Empty valeurs qui représentent des correspondances de sous-chaîne vides entre les marques de ponctuation et les espaces blancs.

Remarques

Lorsqu’une chaîne est délimitée par un ensemble connu de chaînes, vous pouvez utiliser la méthode pour la Split séparer en sous-chaînes.

Les chaînes de délimiteur ne sont pas incluses dans les éléments du tableau retourné. Par exemple, si le separator tableau inclut la chaîne « -- » et que la valeur de la chaîne actuelle instance est « aa--bb--cc », la méthode retourne un tableau qui contient trois éléments : « aa », « bb » et « cc ».

Si cette instance ne contient aucune des chaînes dans separator, le tableau retourné se compose d’un seul élément qui contient cette instance.

Si le options paramètre est RemoveEmptyEntries et que la longueur de ce instance est égale à zéro, la méthode retourne un tableau vide.

Chaque élément de separator définit un délimiteur distinct qui se compose d’un ou plusieurs caractères. Si l’argument options est Noneet que deux délimiteurs sont adjacents ou si un délimiteur est trouvé au début ou à la fin de cette instance, l’élément de tableau correspondant contient String.Empty. Par exemple, si separator inclut deux éléments, « - » et « _ », la valeur de la chaîne instance est « -_aa-_ », et la valeur de l’argument options est None, la méthode retourne un tableau de chaînes avec les cinq éléments suivants :

  1. String.Empty, qui représente la chaîne vide qui précède la sous-chaîne « - » à l’index 0.

  2. String.Empty, qui représente la chaîne vide entre la sous-chaîne « - » à l’index 0 et la sous-chaîne « _ » à l’index 1.

  3. « aa ».

  4. String.Empty, qui représente la chaîne vide qui suit la sous-chaîne « - » à l’index 4.

  5. String.Empty, qui représente la chaîne vide qui suit la sous-chaîne « _ » à l’index 5.

Tableau de séparateurs

Si l’un des éléments dans separator se compose de plusieurs caractères, la sous-chaîne entière est considérée comme un délimiteur. Par exemple, si l’un des éléments dans separator est « 10 », la tentative de fractionnement de la chaîne « This10is10a10string . » renvoie le tableau de quatre éléments suivant : { « This », « is », « a », « string ». }.

Si le separator paramètre est null ou ne contient pas de chaînes non vides, les espaces blancs sont supposés être les délimiteurs. Les espaces blancs sont définis par la norme Unicode et la Char.IsWhiteSpace méthode retourne true s’ils lui sont passés.

Pour passer null pour le string[] separator paramètre, vous devez indiquer le type de pour null lever l’ambiguïté de l’appel à partir d’autres surcharges, telles que Split(Char[], StringSplitOptions). L’exemple suivant montre plusieurs façons d’identifier sans ambiguïté cette surcharge.

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) |> ignore

phrase.Split(null :> string[], StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: string[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, String()),
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New String() {},
                     StringSplitOptions.RemoveEmptyEntries)

Détails de la comparaison

La Split méthode extrait les sous-chaînes de cette chaîne qui sont délimitées par une ou plusieurs chaînes dans le separator paramètre et retourne ces sous-chaînes en tant qu’éléments d’un tableau.

La Split méthode recherche des délimiteurs en effectuant des comparaisons à l’aide de règles de tri ordinale respectant la casse. Pour plus d’informations sur les tris de mots, de chaînes et ordinaux, consultez l’énumération System.Globalization.CompareOptions .

La Split méthode ignore tout élément dont la separator valeur est null ou la chaîne vide («  »).

Pour éviter des résultats ambigus lorsque les chaînes dans separator ont des caractères communs, l’opération Split se poursuit du début à la fin de la valeur de l’instance et correspond au premier élément de separator qui est égal à un délimiteur dans le instance. L’ordre dans lequel les sous-chaînes sont rencontrées dans le instance est prioritaire sur l’ordre des éléments dans separator.

Prenons l’exemple d’un instance dont la valeur est « abcdef ». Si le premier élément dans separator était « ef » et le second élément était « bcde », le résultat de l’opération de fractionnement serait un tableau de chaînes qui contient deux éléments, « a » et « f ». Cela est dû au fait que la sous-chaîne dans le instance, « bcde », est rencontrée et correspond à un élément dans separator avant que la sous-chaîne « f » ne soit rencontrée.

Toutefois, si le premier élément de separator était « bcd » et le deuxième élément était « bc », le résultat de l’opération de fractionnement serait un tableau de chaînes qui contient deux éléments, « a » et « ef ». Cela est dû au fait que « bcd » est le premier délimiteur dans separator qui correspond à un délimiteur dans le instance. Si l’ordre des séparateurs a été inversé de sorte que le premier élément était « bc » et le deuxième élément était « bcd », le résultat serait un tableau de chaînes qui contient deux éléments, « a » et « def ».

Considérations relatives aux performances

Les Split méthodes allouent de la mémoire pour l’objet tableau retourné et un String objet pour chaque élément de tableau. Si votre application nécessite des performances optimales ou si la gestion de l’allocation de mémoire est essentielle dans votre application, envisagez d’utiliser la IndexOf méthode ou IndexOfAny et éventuellement la Compare méthode pour localiser une sous-chaîne dans une chaîne.

Si vous fractionnement une chaîne au niveau d’un caractère séparateur, utilisez la IndexOf méthode ou IndexOfAny pour localiser un caractère de séparateur dans la chaîne. Si vous fractionnement une chaîne au niveau d’une chaîne de séparation, utilisez la IndexOf méthode ou IndexOfAny pour localiser le premier caractère de la chaîne de séparation. Utilisez ensuite la Compare méthode pour déterminer si les caractères qui suivent ce premier caractère sont égaux aux caractères restants de la chaîne de séparation.

En outre, si le même ensemble de caractères est utilisé pour fractionner des chaînes dans plusieurs Split appels de méthode, envisagez de créer un tableau unique et de le référencer dans chaque appel de méthode. Cela réduit considérablement la surcharge supplémentaire de chaque appel de méthode.

Notes pour les appelants

Dans .NET Framework 3.5 et versions antérieures, si la Split(Char[]) méthode est passée à un separator qui est null ou ne contient pas de caractères, la méthode utilise un jeu d’espaces blancs légèrement différent pour fractionner la chaîne que la Trim(Char[]) méthode pour découper la chaîne. À compter de .NET Framework 4, les deux méthodes utilisent un jeu identique de caractères d’espace blanc Unicode.

S’applique à

Split(Char, Int32, StringSplitOptions)

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

Divise une chaîne en un nombre maximal de sous-chaînes en fonction d’un caractère de délimitation spécifié et, éventuellement, d’options. Divise une chaîne en un nombre maximal de sous-chaînes en fonction du séparateur de caractères fourni, en omettant éventuellement les sous-chaînes vides du résultat.

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()

Paramètres

separator
Char

Caractère qui délimite les sous-chaînes de cette instance.

count
Int32

Nombre maximal d’éléments attendus dans le tableau.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau qui contient au maximum count sous-chaînes de cette instance, qui sont délimitées par separator.

Remarques

Si la chaîne a déjà été fractionnée count - 1 fois, mais que la fin de la chaîne n’a pas été atteinte, la dernière chaîne du tableau retourné contient la sous-chaîne de fin restante de cette instance, non affectée.

S’applique à

Split(Char[], Int32, StringSplitOptions)

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

Divise une chaîne en un nombre maximal de sous-chaînes en fonction de caractères de délimitation spécifiés et, éventuellement, d’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()

Paramètres

separator
Char[]

Tableau de caractères qui délimitent les sous-chaînes de cette chaîne, tableau vide qui ne contient pas de délimiteur ni de null.

count
Int32

Nombre maximal de sous-chaînes à retourner.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau qui contient les sous-chaînes de cette chaîne qui sont délimitées par un ou plusieurs caractères dans separator. Pour plus d'informations, consultez la section Remarques.

Attributs

Exceptions

count est un nombre négatif.

options ne fait pas partie des valeurs StringSplitOptions.

Exemples

L’exemple suivant utilise l’énumération StringSplitOptions pour inclure ou exclure les sous-chaînes générées par la Split méthode .

// This example demonstrates the String.Split(Char[], Boolean) and 
//                               String.Split(Char[], Int32, Boolean) methods
using 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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void 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:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
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 function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    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:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

Remarques

Les caractères délimiteurs ne sont pas inclus dans les éléments du tableau retourné.

Si cette instance ne contient aucun des caractères dans separator, ou si le paramètre a la count valeur 1, le tableau retourné se compose d’un seul élément qui contient ce instance.

Si le separator paramètre est null ou ne contient aucun caractère, les espaces blancs sont supposés être les délimiteurs. Les espaces blancs sont définis par la norme Unicode et la Char.IsWhiteSpace méthode retourne true s’ils lui sont passés.

Pour passer null pour le char[] separator paramètre, vous devez indiquer le type de pour null lever l’ambiguïté de l’appel à partir d’autres surcharges, telles que Split(String[], Int32, StringSplitOptions). L’exemple suivant montre plusieurs façons d’identifier sans ambiguïté cette surcharge.

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) |> ignore

phrase.Split(null :> char[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: char[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, Char()), 3,
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New Char() {}, 3,
                     StringSplitOptions.RemoveEmptyEntries)

Si le count paramètre est égal à zéro, ou si le options paramètre est RemoveEmptyEntries et que la longueur de cette instance est égale à zéro, un tableau vide est retourné.

Chaque élément de separator définit un caractère délimiteur distinct. Si le options paramètre est Noneet que deux délimiteurs sont adjacents ou si un délimiteur est trouvé au début ou à la fin de cette instance, l’élément de tableau correspondant contient Empty.

Si cette instance contient plus count de sous-chaînes, les premières count sous-chaînes moins 1 sont retournées dans les premiers count éléments moins 1 de la valeur de retour, et les caractères restants dans cette instance sont retournés dans le dernier élément de la valeur de retour.

Si count est supérieur au nombre de sous-chaînes, les sous-chaînes disponibles sont retournées et aucune exception n’est levée.

Considérations relatives aux performances

Les Split méthodes allouent de la mémoire pour l’objet tableau retourné et un String objet pour chaque élément de tableau. Si votre application nécessite des performances optimales ou si la gestion de l’allocation de mémoire est essentielle dans votre application, envisagez d’utiliser la IndexOf méthode ou IndexOfAny et éventuellement la Compare méthode pour localiser une sous-chaîne dans une chaîne.

Si vous fractionnement une chaîne au niveau d’un caractère séparateur, utilisez la IndexOf méthode ou IndexOfAny pour localiser un caractère de séparateur dans la chaîne. Si vous fractionnement une chaîne au niveau d’une chaîne de séparation, utilisez la IndexOf méthode ou IndexOfAny pour localiser le premier caractère de la chaîne de séparation. Utilisez ensuite la Compare méthode pour déterminer si les caractères qui suivent ce premier caractère sont égaux aux caractères restants de la chaîne de séparation.

En outre, si le même ensemble de caractères est utilisé pour fractionner des chaînes dans plusieurs Split appels de méthode, envisagez de créer un tableau unique et de le référencer dans chaque appel de méthode. Cela réduit considérablement la surcharge supplémentaire de chaque appel de méthode.

Notes pour les appelants

Dans .NET Framework 3.5 et versions antérieures, si la Split(Char[]) méthode est passée à un separator qui est null ou ne contient pas de caractères, la méthode utilise un jeu d’espaces blancs légèrement différent pour fractionner la chaîne que la Trim(Char[]) méthode pour découper la chaîne. À compter de .NET Framework 4, les deux méthodes utilisent un jeu identique de caractères d’espace blanc Unicode.

S’applique à

Split(String, Int32, StringSplitOptions)

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

Divise une chaîne en un nombre maximal de sous-chaînes en fonction d’une chaîne de délimitation spécifiée et, éventuellement, d’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()

Paramètres

separator
String

Chaîne qui délimite les sous-chaînes de cette instance.

count
Int32

Nombre maximal d’éléments attendus dans le tableau.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau qui contient au maximum count sous-chaînes de cette instance, qui sont délimitées par separator.

Remarques

Si la chaîne a déjà été fractionnée count - 1 fois, mais que la fin de la chaîne n’a pas été atteinte, la dernière chaîne du tableau retourné contient la sous-chaîne de fin restante de cette instance, non affectée.

S’applique à

Split(String[], Int32, StringSplitOptions)

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

Divise une chaîne en un nombre maximal de sous-chaînes en fonction de chaînes de délimitation spécifiées et, éventuellement, d’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()

Paramètres

separator
String[]

Chaînes qui délimitent les sous-chaînes de cette chaîne, tableau vide qui ne contient pas de délimiteur ni de null.

count
Int32

Nombre maximal de sous-chaînes à retourner.

options
StringSplitOptions

Combinaison au niveau du bit de valeurs d’énumération qui spécifie s’il faut supprimer les sous-chaînes et inclure les sous-chaînes vides.

Retours

String[]

Tableau dont les éléments contiennent les sous-chaînes de cette chaîne qui sont délimitées par une ou plusieurs chaînes dans separator. Pour plus d'informations, consultez la section Remarques.

Attributs

Exceptions

count est un nombre négatif.

options ne fait pas partie des valeurs StringSplitOptions.

Exemples

L’exemple suivant utilise l’énumération StringSplitOptions pour inclure ou exclure les sous-chaînes générées par la Split méthode .

// This example demonstrates the String.Split(Char[], Boolean) and 
//                               String.Split(Char[], Int32, Boolean) methods
using 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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void 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:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
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 function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    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:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

Remarques

Les chaînes de délimiteur ne sont pas incluses dans les éléments du tableau retourné.

Si cette instance ne contient aucune des chaînes dans separator, ou si le paramètre a la count valeur 1, le tableau retourné se compose d’un élément unique qui contient cette instance.

Si le separator paramètre est null ou ne contient aucun caractère, les espaces blancs sont supposés être les délimiteurs. Les espaces blancs sont définis par la norme Unicode et la Char.IsWhiteSpace méthode retourne true s’ils lui sont passés.

Pour passer null pour le string[] separator paramètre, vous devez indiquer le type de pour null lever l’ambiguïté de l’appel à partir d’autres surcharges, telles que Split(Char[], Int32, StringSplitOptions). L’exemple suivant montre plusieurs façons d’identifier sans ambiguïté cette surcharge.

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) |> ignore

phrase.Split(null :> string[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: string[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, String()), 3,
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New String() {}, 3,
                     StringSplitOptions.RemoveEmptyEntries)

Si le count paramètre est égal à zéro, ou si le options paramètre est RemoveEmptyEntries et que la longueur de cette instance est égale à zéro, un tableau vide est retourné.

Chaque élément de separator définit un délimiteur distinct qui se compose d’un ou plusieurs caractères. Si le options paramètre est Noneet que deux délimiteurs sont adjacents ou si un délimiteur est trouvé au début ou à la fin de cette instance, l’élément de tableau correspondant contient Empty.

Si cette instance contient plus count de sous-chaînes, les premières count sous-chaînes moins 1 sont retournées dans les premiers count éléments moins 1 de la valeur de retour, et les caractères restants dans cette instance sont retournés dans le dernier élément de la valeur de retour.

Si count est supérieur au nombre de sous-chaînes, les sous-chaînes disponibles sont retournées et aucune exception n’est levée.

Tableau de séparateurs

Si l’un des éléments dans separator se compose de plusieurs caractères, la sous-chaîne entière est considérée comme un délimiteur. Par exemple, si l’un des éléments dans separator est « 10 », la tentative de fractionnement de la chaîne « This10is10a10string . » renvoie ce tableau de quatre éléments : { « This », « is », « a », « string. » }.

Détails de la comparaison

La Split méthode extrait les sous-chaînes de cette chaîne qui sont délimitées par une ou plusieurs chaînes dans le separator paramètre et retourne ces sous-chaînes en tant qu’éléments d’un tableau.

La Split méthode recherche des délimiteurs en effectuant des comparaisons à l’aide de règles de tri ordinale respectant la casse. Pour plus d’informations sur les tris de mots, de chaînes et ordinaux, consultez l’énumération System.Globalization.CompareOptions .

La Split méthode ignore tout élément dont la separator valeur est null ou la chaîne vide («  »).

Pour éviter des résultats ambigus lorsque les chaînes dans separator ont des caractères communs, la Split méthode passe du début à la fin de la valeur de l’instance et correspond au premier élément de separator qui est égal à un délimiteur dans le instance. L’ordre dans lequel les sous-chaînes sont rencontrées dans le instance est prioritaire sur l’ordre des éléments dans separator.

Prenons l’exemple d’un instance dont la valeur est « abcdef ». Si le premier élément dans separator était « ef » et le second élément était « bcde », le résultat de l’opération de fractionnement serait « a » et « f ». Cela est dû au fait que la sous-chaîne dans le instance, « bcde », est rencontrée et correspond à un élément dans separator avant que la sous-chaîne « f » ne soit rencontrée.

Toutefois, si le premier élément de separator était « bcd » et le deuxième élément était « bc », le résultat de l’opération de fractionnement serait « a » et « ef ». Cela est dû au fait que « bcd » est le premier délimiteur dans separator qui correspond à un délimiteur dans le instance. Si l’ordre des séparateurs a été inversé de sorte que le premier élément était « bc » et le deuxième élément était « bcd », le résultat serait « a » et « def ».

Considérations relatives aux performances

Les Split méthodes allouent de la mémoire pour l’objet tableau retourné et un String objet pour chaque élément de tableau. Si votre application nécessite des performances optimales ou si la gestion de l’allocation de mémoire est essentielle dans votre application, envisagez d’utiliser la IndexOf méthode ou IndexOfAny et éventuellement la Compare méthode pour localiser une sous-chaîne dans une chaîne.

Si vous fractionnement une chaîne au niveau d’un caractère séparateur, utilisez la IndexOf méthode ou IndexOfAny pour localiser un caractère de séparateur dans la chaîne. Si vous fractionnement une chaîne au niveau d’une chaîne de séparation, utilisez la IndexOf méthode ou IndexOfAny pour localiser le premier caractère de la chaîne de séparation. Utilisez ensuite la Compare méthode pour déterminer si les caractères qui suivent ce premier caractère sont égaux aux caractères restants de la chaîne de séparation.

En outre, si le même ensemble de caractères est utilisé pour fractionner des chaînes dans plusieurs Split appels de méthode, envisagez de créer un tableau unique et de le référencer dans chaque appel de méthode. Cela réduit considérablement la surcharge supplémentaire de chaque appel de méthode.

Notes pour les appelants

Dans .NET Framework 3.5 et versions antérieures, si la Split(Char[]) méthode est passée à un separator qui est null ou ne contient pas de caractères, la méthode utilise un jeu d’espaces blancs légèrement différent pour fractionner la chaîne que la Trim(Char[]) méthode pour découper la chaîne. À compter de .NET Framework 4, les deux méthodes utilisent un jeu identique de caractères d’espace blanc Unicode.

S’applique à