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::vectorcan grow withpush_back. - C#’s
Splitaccepts several delimiters in one call.std::getlinetakes one character, so C++ needs a loop orfind_first_ofto handle more. - C#’s
RemoveEmptyEntriesoption has no single-call equivalent in C++. You add anifcheck 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.