Splitting Strings

What Does Split() Do in C#?

In C#, string.Split() returns an array of the pieces between delimiters. See the char and options overloads, empty entries, and how it compares to C++.

On this page
  1. The basic call
  2. Empty pieces
  3. More than one delimiter
  4. Compared with C++

In C#, Split() is a method on the string type. It cuts a string into pieces wherever it finds a delimiter, and returns the pieces as an array of strings. The original string keeps its text, because C# strings cannot be changed in place.

The basic call

Pass the delimiter character to Split, then loop over the array:

string fruit = "apple,banana,cherry";
string[] parts = fruit.Split(',');

foreach (string part in parts)
{
    Console.WriteLine(part);
}

The program prints apple, banana and cherry, one per line. Each call returns a new array, so fruit still holds the full text.

Empty pieces

A delimiter next to another delimiter creates an empty piece. "a,,b".Split(',') returns three items: a, an empty string and b. A delimiter at the end also adds an empty item, so "a,b,".Split(',') returns a, b and an empty string. To drop the empty items, pass StringSplitOptions.RemoveEmptyEntries:

string[] parts = "a,,b".Split(',', StringSplitOptions.RemoveEmptyEntries);
// parts is { "a", "b" }

More than one delimiter

Pass several characters and Split uses any of them as a delimiter:

string[] words = "red,green;blue".Split(',', ';');
// words is { "red", "green", "blue" }

Called with no arguments, Split treats white space as the delimiter.

Compared with C++

C++ has no Split() method on std::string. The usual replacement is std::getline with a std::stringstream, shown in How to Use split(). The two languages differ in a few ways:

  • C# returns an array with a fixed length. A C++ std::vector can grow with push_back.
  • C#’s Split accepts several delimiters in one call. std::getline takes one character, so C++ needs a loop or find_first_of to handle more.
  • C#’s RemoveEmptyEntries option has no single-call equivalent in C++. You add an if check that skips empty pieces.

If you are reading C# code, the key points are that Split returns an array, keeps empty entries unless you tell it not to, and accepts several delimiters.

The complete guide to splitting strings

How to Split a String by a Delimiter in C++
Read the guide

Keep exploring

Guides from other topics

All topics →