Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

String.Split-Methode

 

Veröffentlicht: Oktober 2016

Gibt ein Zeichenfolgenarray zurück, das die Teilzeichenfolgen dieser Instanz enthält, die durch Elemente eines angegebenen Zeichenfolgen- oder Unicode-Zeichenarrays getrennt sind.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

NameBeschreibung
System_CAPS_pubmethodSplit(Char[])

Unterteilt eine Zeichenfolge anhand der Zeichen in einem Array in Teilzeichenfolgen.

System_CAPS_pubmethodSplit(Char[], Int32)

Unterteilt eine Zeichenfolge anhand der Zeichen in einem Array in eine maximale Anzahl von Teilzeichenfolgen. Sie geben außerdem die maximale Anzahl der zurückzugebenden Teilzeichenfolgen an.

System_CAPS_pubmethodSplit(Char[], Int32, StringSplitOptions)

Unterteilt eine Zeichenfolge anhand der Zeichen in einem Array in eine maximale Anzahl von Teilzeichenfolgen.

System_CAPS_pubmethodSplit(Char[], StringSplitOptions)

Unterteilt eine Zeichenfolge anhand der Zeichen in einem Array in Teilzeichenfolgen. Sie können angeben, ob die Teilzeichenfolgen auch leere Arrayelemente umfassen.

System_CAPS_pubmethodSplit(String[], Int32, StringSplitOptions)

Unterteilt eine Zeichenfolge anhand der Zeichenfolgen in einem Array in eine maximale Anzahl von Teilzeichenfolgen. Sie können angeben, ob die Teilzeichenfolgen auch leere Arrayelemente umfassen.

System_CAPS_pubmethodSplit(String[], StringSplitOptions)

Unterteilt eine Zeichenfolge anhand der Zeichenfolgen in einem Array in Teilzeichenfolgen. Sie können angeben, ob die Teilzeichenfolgen auch leere Arrayelemente umfassen.

Split is used to break a delimited string into substrings. You can use either a character array to specify zero, one, or multiple delimiting characters (the Split(Char[]) method), or you can use a character array to specify zero, one, or multiple delimiting strings. Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to determine whether empty strings are included in the returned substrings (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods, or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

System_CAPS_importantWichtig

For more detailed information on the Overload:System.String.Split method, as well as for examples that call each overload, see the documentation for the individual overloads of Overload:System.String.Split.

The M:System.String.Split(System.Char[]) method is not always the best way to break a delimited string into substrings. If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider the following alternatives.

If your strings conform to a fixed pattern, you can use a regular expression to extract and handle their elements. For example, if strings take the form "numberoperandnumber" you can use a regular expression to extract and handle the string's elements. Here's an example:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                               "42 - 18", "12 * 7",
                               "2, 4, 6, 8" };
      String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";
      foreach (var expression in expressions)
         foreach (Match m in Regex.Matches(expression, pattern)) {
            int value1 = Int32.Parse(m.Groups[1].Value);
            int value2 = Int32.Parse(m.Groups[3].Value);
            switch (m.Groups[2].Value)
            {
               case "+":
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2);
                  break;
               case "-":
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2);
                  break;
               case "*":
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2);
                  break;
               case "/":
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2);
                  break;
            }
         }
   }
}
// The example displays the following output:
//       16 + 21 = 37
//       31 * 3 = 93
//       28 / 3 = 9.33
//       42 - 18 = 24
//       12 * 7 = 84

The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:

Pattern

Description

(\d+)

Match one or more decimal digits. This is the first capturing group.

\s+

Match one or more whitespace characters.

([-+*/])

Match an arithmetic operator sign (+, -, *, or /). This is the second capturing group.

\s+

Match one or more whitespace characters.

(\d+)

Match one or more decimal digits. This is the third capturing group.

You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. This is a common scenario when either of these conditions occurs:

  • One or more of the delimiter characters does not always serve as a delimiter in the T:System.String instance.

  • The sequence and number of delimiter characters is variable or unknown.

For example, the M:System.String.Split(System.Char[]) method cannot be used to split the following string, because the number of \n (in C#) or vbCrLf (in Visual Basic) characters is variable, and they do not always serve as delimiters.


[This is captured\ntext.]\n\n[\n[This is more captured text.]\n]
\n[Some more captured text:\n   Option1\n   Option2][Terse text.] 

A regular expression can split this string easily, as the following example shows.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String input = "[This is captured\ntext.]\n\n[\n" +
                     "[This is more captured text.]\n]\n" +
                     "[Some more captured text:\n   Option1" +
                     "\n   Option2][Terse text.]";
      String pattern = @"\[([^\[\]]+)\]";
      int ctr = 0;
      foreach (Match m in Regex.Matches(input, pattern))
         Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value);
   }
}
// The example displays the following output:
//       1: This is captured
//       text.
//       2: This is more captured text.
//       3: Some more captured text:
//          Option1
//          Option2
//       4: Terse text.

The regular expression pattern \[([^\[\]]+)\] is defined like this:

Pattern

Description

\[

Match an opening bracket.

([^\[\]]+)

Match any character that is not an opening or a closing bracket one or more times. This is the first capturing group.

\]

Match a closing bracket.

The M:System.Text.RegularExpressions.Regex.Split(System.String) method is almost identical to M:System.String.Split(System.Char[]), except that it splits a string based on a regular expression pattern instead of a fixed character set. For example, the following example uses the M:System.Text.RegularExpressions.Regex.Split(System.String) method to split a string that contains substrings delimited by various combinations of hyphens and other characters.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String input = "abacus -- alabaster - * - atrium -+- " +
                     "any -*- actual - + - armoir - - alarm";
      String pattern = @"\s-\s?[+*]?\s?-\s";
      String[] elements = Regex.Split(input, pattern);
      foreach (var element in elements)
         Console.WriteLine(element);
   }
}
// The example displays the following output:
//       abacus
//       alabaster
//       atrium
//       any
//       actual
//       armoir
//       alarm

The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:

Pattern

Description

\s-

Match a whitespace character followed by a hyphen.

\s?

Match zero or one whitespace character.

[+*]?

Match zero or one occurrence of either the + or * character.

\s?

Match zero or one whitespace character.

-\s

Match a hyphen followed by a whitespace character.

If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. You can then call the M:System.String.Substring(System.Int32) method to extract the substring that you want. The string comparison methods include:

  • IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

  • IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

  • LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

  • LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

The following example uses the M:System.String.IndexOf(System.Char) method to find the periods in a string. It then uses the M:System.String.Substring(System.Int32) method to return full sentences.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      String value = "This is the first sentence in a string. " +
                     "More sentences will follow. For example, " +
                     "this is the third sentence. This is the " +
                     "fourth. And this is the fifth and final " +
                     "sentence.";
      var sentences = new List<String>();
      int position = 0;
      int start = 0;
      // Extract sentences from the string.
      do {
         position = value.IndexOf('.', start);
         if (position >= 0) {
            sentences.Add(value.Substring(start, position - start + 1).Trim());
            start = position + 1;
         }
      } while (position > 0);

      // Display the sentences.
      foreach (var sentence in sentences)
         Console.WriteLine(sentence);
   }
}
// The example displays the following output:
//       This is the first sentence in a string.
//       More sentences will follow.
//       For example, this is the third sentence.
//       This is the fourth.
//       And this is the fifth and final sentence.
Zurück zum Anfang
Anzeigen: