You are wondering what the StringSplitOptions parameter on the Split method in the C# language does, and how you can use it to make your program simpler and faster. It is an enumerated constant and very useful. Here we look at how you can use StringSplitOptions.RemoveEmptyEntries and how it affects the behavior of the Split method.
First, you must include the System namespace at the top of your file to use the StringSplitOptions enumeration without a fully qualified name. The two values of StringSplitOptions, None and RemoveEmptyEntries, are actually just integers that tell Split how to work. The next example shows their usage.
=== Program that uses StringSplitOptions (C#) ===
using System;
class Program
{
static void Main()
{
//
// Input string contain separators.
//
string value1 = "man,woman,child,,,bird";
char[] delimiter1 = new char[] { ',' }; // <-- Split on these
//
// Use StringSplitOptions.None.
//
string[] array1 = value1.Split(delimiter1, StringSplitOptions.None);
Console.WriteLine("--- StringSplitOptions.None ---");
foreach (string entry in array1)
{
Console.WriteLine(entry);
}
//
// Use StringSplitOptions.RemoveEmptyEntries.
//
string[] array2 = value1.Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("--- StringSplitOptions.RemoveEmptyEntries ---");
foreach (string entry in array2)
{
Console.WriteLine(entry);
}
}
}
=== Output of the program ===
--- StringSplitOptions.None ---
man
woman
child
bird
--- StringSplitOptions.RemoveEmptyEntries ---
man
woman
child
bird Notes on preceding example. The input string in the example contains 5 commas, which are the delimiters. However, two fields between commas are 0 characters long (empty). In the first call to Split, these fields are put into the result array. In the second call to Split, where we specify StringSplitOptions.RemoveEmptyEntries, the two empty fields are not in the result array.
Here we saw how you can use the StringSplitOptions.RemoveEmptyEntries enumerated constant as the second parameter in the Split method. The enumeration is in the System namespace. By removing empty entries, you can simplify some logic. However, sometimes empty fields are useful for maintaining the order of your fields.