Windows Dev Center

Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

String.Split Method (Char())

Splits a string into substrings that are based on the characters in an array.

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

'Declaration
Public Function Split ( _
	ParamArray separator As Char() _
) As String()

Parameters

separator
Type: System.Char()

A character array that delimits the substrings in this string, an empty array that contains no delimiters, or Nothing.

Return Value

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

When a string is delimited by a known set of characters, you can use the Split method to separate it into substrings. For other ways to extract substrings from a string, see the Alternatives to String.Split section.

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

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

If the separator argument is Nothing or contains no characters, the method treats white-space characters as the delimiters. White-space characters are defined by the Unicode standard; they return true if they are passed to the Char.IsWhiteSpace method.

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

String value

Separator

Returned array

"42, 12, 19"

new Char[] {',', ' '} (C#)

Char() = {","c, " "c}) (Visual Basic)

{"42", "", "12", "", "19"}

"42..12..19"

new Char[] {'.'} (C#)

Char() = {"."c} (Visual Basic)

{"42", "", "12", "", "19"}

"Banana"

new Char[] {'.'} (C#)

Char() = {"."c} (Visual Basic)

{"Banana"}

"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)

new Char[] {} (C#)

Char() = {} (Visual Basic)

{"Darb", "Smarba"}

"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)

null (C#)

Nothing (Visual Basic)

{"Darb", "Smarba"}

Alternatives to String.Split

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.

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:

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim expressions() As String = { "16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8" }

      Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)" 
      For Each expression In expressions
         For Each m As Match in Regex.Matches(expression, pattern)
            Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
            Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
            Select Case m.Groups(2).Value
               Case "+"
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
               Case "-"
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
               Case "*"
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
               Case "/"
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
            End Select 
         Next 
      Next 
   End Sub 
End Module 
' 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.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
      Dim pattern As String = "\[([^\[\]]+)\]" 
      Dim ctr As Integer = 0
      For Each m As Match In Regex.Matches(input, pattern)
         ctr += 1
         Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
      Next 
   End Sub 
End Module 
' 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.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoir - - alarm" 
      Dim pattern As String = "\s-\s?[+*]?\s?-\s" 
      Dim elements() As String = Regex.Split(input, pattern)
      For Each element In elements
         Console.WriteLine(element)
      Next 
   End Sub 
End Module 
' 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 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.

Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim value As String = "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." 
      Dim sentences As New List(Of String)
      Dim position As Integer = 0
      Dim start As Integer = 0
      ' Extract sentences from the string. 
      Do
         position = value.IndexOf("."c, start)
         If position >= 0 Then
            sentences.Add(value.Substring(start, position - start + 1).Trim())
            start = position + 1
         End If 
      Loop While position > 0

      ' Display the sentences. 
      For Each sentence In sentences
         Console.WriteLine(sentence)
      Next 
   End Sub 
End Module 
' 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.

Performance Considerations

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

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

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

Notes to Callers

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

The following example demonstrates how to extract individual words from a block of text by treating white space and punctuation marks as delimiters. The character array passed to the separator parameter of the String.Split(Char()) method consists of a space character and a tab character, together with some common punctuation symbols.

Public Class SplitTest
    Public Shared Sub Main()
        Dim words As String = "This is a list of words, with: a bit of punctuation" + _
                              vbTab + "and a tab character." 
        Dim split As String() = words.Split(New [Char]() {" "c, ","c, "."c, ":"c, CChar(vbTab) })

        For Each s As String In  split
            If s.Trim() <> "" Then
                Console.WriteLine(s)
            End If 
        Next s
    End Sub 'Main
End Class 'SplitTest
' The example displays the following output to the console: 
'       This 
'       is 
'       a 
'       list 
'       of 
'       words 
'       with 
'       a 
'       bit 
'       of 
'       punctuation 
'       and 
'       a 
'       tab 
'       character

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library
Show:
© 2015 Microsoft