BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Convert Comma-Separated Strings to String Arrays

Integrating with legacy systems often includes receiving comma-separated lists of string values. To process these values, you may want to convert the comma-separated information to a simple array containing one element for each of the items.

Tabular Data

Many systems provide the ability to store tabular information in comma-separated value (CSV) files. Although CSV files do not provide the level of descriptiveness of XML or the flexibility of database tables, they are small, transportable and of an accepted standard. This is why they are often used for integration between systems.

When processing CSV information it is common to transform the strings of comma-separated values into arrays. Such arrays contain one element for each value a CSV line. With the .NET framework we can use Split method of the String class for this purpose.

String.Split Method

The Split method requires a parameter containing a character array. Each item in the array is a potential delimiting character. Handily, the parameter is a Parameter Array. This allows multiple characters to be included directly in the method without initialising the array beforehand.

The following code splits a comma-separated list:

string fruit = "Apple,Banana,Orange,Strawberry";
string[] split = fruit.Split(',');

foreach (string item in split)
{
    Console.WriteLine(item);
}
    
/* OUTPUT

Apple
Banana
Orange
Strawberry

*/

The following example is similar but this time the delimiting characters are the bar (|) and the comma. Both cause the generation of an additional result in the array.

string fruit = "Apple|Banana,Orange|Strawberry";
string[] split = fruit.Split('|', ',');

foreach (string item in split)
{
    Console.WriteLine(item);
}

/* OUTPUT

Apple
Banana
Orange
Strawberry

*/

NB: The techniques in this article are not suitable when parsing CSV files where the individual data items can contain the delimiting characters. The article demonstrates the use of the Split method only and will give incorrect results for strings such as:

John Smith,"Jones, Bill",Mel Parker
15 February 2008