Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.
Traduzione
Inglese

Metodo String.Split (String[], StringSplitOptions)

 

Suddivide una stringa in sottostringhe in base alle stringhe in una matrice. È possibile specificare se le sottostringhe includono elementi della matrice vuota.

Spazio dei nomi:   System
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(false)]
public string[] Split(
	string[] separator,
	StringSplitOptions options
)

Parametri

separator
Type: System.String[]

Matrice di stringhe che delimita le sottostringhe di questa stringa, matrice vuota senza delimitatori o null.

options
Type: System.StringSplitOptions

StringSplitOptions.RemoveEmptyEntries per omettere gli elementi di matrice vuoti dalla matrice restituita; StringSplitOptions.None per includere tali elementi.

Valore restituito

Type: System.String[]

Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da una o più stringhe indicate in separator. Per altre informazioni, vedere la sezione Osservazioni.

Exception Condition
ArgumentException

options non è uno dei valori di StringSplitOptions.

When a string is delimited by a known set of strings, you can use the M:System.String.Split(System.String[],System.StringSplitOptions) method to separate it into substrings.

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

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

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

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

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

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

  3. "aa",

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

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

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

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

If the separator parameter in the call to this method overload is null, compiler overload resolution fails. To unambiguously identify the called method, your code must indicate the type of the null. The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split((string[]) null, StringSplitOptions.RemoveEmptyEntries);

words = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);

The M:System.String.Split(System.String[],System.StringSplitOptions) method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

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

The M:System.String.Split(System.String[],System.StringSplitOptions) method ignores any element of separator whose value is null or the empty string ("").

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

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

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

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

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

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

Note per i chiamanti:

In the net_v35_short and earlier versions, if the M:System.String.Split(System.Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the M:System.String.Trim(System.Char[]) method does to trim the string. In the net_v40_short, both methods use an identical set of Unicode white-space characters.

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

using System;

class Example 
{
   public static void Main() 
   {
      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   \"{0}\".", source);
      Console.WriteLine();
      Console.WriteLine("Using the delimiter string:\n   \"{0}\"", 
                        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("   ");
      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 ({0} elements):", 
                        result.Length);
      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'

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

using System;

public class Example
{
   public static void Main()
   {
      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

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

Universal Windows Platform
Disponibile da 8
.NET Framework
Disponibile da 2.0
Libreria di classi portabile
Supportato in: piattaforme .NET portabili
Silverlight
Disponibile da 2.0
Windows Phone Silverlight
Disponibile da 7.0
Windows Phone
Disponibile da 8.1
Torna all'inizio
Mostra: