Export (0) Print
Expand All

String.Split Method

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

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method Supported by the XNA Framework Supported by Portable Class Library Split(Char[]) Splits a string into substrings that are based on the characters in an array.
Public method Supported by Portable Class Library Split(Char[], Int32) Splits a string into a maximum number of substrings based on the characters in an array. You also specify the maximum number of substrings to return.
Public method Supported by Portable Class Library Split(Char[], StringSplitOptions) Splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements.
Public method Supported by Portable Class Library Split(String[], StringSplitOptions) Splits a string into substrings based on the strings in an array. You can specify whether the substrings include empty array elements.
Public method Supported by Portable Class Library Split(Char[], Int32, StringSplitOptions) Splits a string into a maximum number of substrings based on the characters in an array.
Public method Supported by Portable Class Library Split(String[], Int32, StringSplitOptions) Splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements.
Top

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 and Split methods).

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

Regular expressions

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 "number operand number" 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 String instance.

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

For example, the Split 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 Regex.Split method is almost identical to String.Split, 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 Regex.Split 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.

Search methods and the Substring method

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 Substring 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 IndexOf method to find the periods in a string. It then uses the Substring 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.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft