The Magic of the C# Split String Method

shutterstock_19272514One day, you may encounter a C# programming problem that requires you to manipulate string variables. Your ability to figure out how to split a string may determine how successful you are in accomplishing your programming goal. The .NET Framework contains an incredibly useful Split method that enables you to divide a string into components using a single line of code.

New to C#?  Learn coding secrets at Udemy.

Splitting a C# String into Components using the Split Method

String variables can come from a variety of sources. For example, one of your methods might store the contents of a text box in a string variable named orderDescription. Another method could read the contents of a text file and store its text in a variable named textFileContents. Unless you need to examine or manipulate individual characters or words that reside in a string, you may have no need to split it.

Suppose you were working on a word game that allowed users to type sentences into a text box. One interesting game control might be a button people could click that randomized the sentence’s words. If you knew how to split a string into separate substrings, you could code this functionality easily.

Assume your TextBox contained the string “Summer days are fun.” The code sample below shows some of the statements you need to split a TextBox control’s text into words:

char delimiter = '  ‘;

string sentence = textBox1.Text;

This first statement creates a char variable named delimiter. It stores a blank character.

The next statement stores the contents of a TextBox control named textBox1 in a string variable named sentence. Now all you need to do is execute the Split method and store the sentence variable’s words in another variable, as shown below:

string[] words;

words = sentence.Split(delimiter);

The first statement creates a string array named words. An array is a structure that can hold multiple values. In C#, one way to create an array is to place square brackets after a data type, as shown in this example.

Need to learn about arrays? Let Udemy help you master them.

The final statement executes the Split method. That method examines the sentence variable and splits the parts that are separated by the delimiter. Because our delimiter is a space, C# populates the words array with the following four elements:

  • Summer
  • days
  • are
  • fun

You are now free to use the words array named words any way you like. If you wanted to use it to generate random words from the original sentence, you could write a random number generator method and pass it the array.

Real World C# Split String Use Cases

The “Summer days are fun” example is simple, but it demonstrates how to solve several string manipulation problems easily. You’ll find it especially useful for computing word counts. For instance, if a user typed a few hundred words into a RichTextBox, you could split its text into an array and examine the array’s Length property, as show below:

int wordCount = words.Length;

The wordCount variable holds the array’s length. If you ever need to split text strings that are separated by line break characters, you’re in luck — the Split method handles that task perfectly. Here’s a quick code sample:

char delimiter = '\n';

string richTextBoxText = richTextBox1.Text;

string[] phrases = richTextBoxText.Split(delimiter);

The delimiter in this instance is the newline character. If your RichTextBox contained three phrases separated by line breaks, the Split method would store those in the phrases array. Your application could then access any member of the array to examine its value.

Advanced C# Split String Techniques: Using Multiple Delimiters

In the real world, you may encounter scenarios where a string contains several delimiters that you’d like to use to split your string. Consider the following string:

“cell phone,  laptop * microwave * digital camera, MP3 player”

This string contains substrings separated by two types of delimiters: commas and asterisks. Like many C# methods, the Split method has several overloads. Overloading is a process where developers create multiple variations of a method where each method has a unique signature. For example, two methods named Summarize might accept different types of arguments.

Want to discover more helpful classes? Learn about the .NET Framework.

If you’d like the Split method to accept two delimiters, simply call the overload method that accepts a string array as an input parameter. The following code demonstrates this:

string textString = “cell phone,  laptop * microwave * digital camera, MP3 player”;

string[] delimiters = new string[] { ",", "*" };

string[] items = richTextBoxText.Split(delimiters, StringSplitOptions.None)

The textString variable holds the text string you’d like to split, but pay close attention to the next statement. The right half of that equation creates a new string array that contains two elements – your comma delimiter and your asterisk delimiter. The statement stores that array in the delimiters array.

The final statement executes the Split method that splits the textString variable into five elements: cell phone, laptop, microwave, digital camera and MP3 player. Those elements go into the items array that you can manipulate and examine as needed.  Name your arrays anything you like that’s meaningful to you.

Splitting Strings in C#: Lessons Learned

As you can see, it only takes a single statement to split a string. All the other code shown in these perform secondary tasks, such as assigning values to delimiter variables. If you review the final Split statement shown in the previous example, you’ll see that it contains a StringSplitOptions parameter:

string[] items = richTextBoxText.Split(delimiters, StringSplitOptions.None)

You must include that parameter when you pass delimiter arrays to the Split method. In this example, the StringSplitOptions’s value is “None.” That value tells C# to return array elements that contain empty strings. If you don’t want C# to return array elements that contain empty strings, change None to RemoveEmptyEntries, as shown in the sample below:

string[] items = richTextBoxText.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);

An excellent way to learn advanced C# programming is to use Visual Studio’s Intellisense. For instance, after you type .Split(, Visual Studio displays a box that allows you to view the six overloads for the Split method. Simply press your keyboard’s “Up” and “Down” arrows to review those overloads. In our samples, we only reviewed two overloads that should handle many of your programming needs.

As always, experimentation and study can help you become a C# programming guru.