 .NET 1.1Convert 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 these text 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 holding information for integration between systems.
When processing CSV information it is common to transform the long strings of comma-separated values into simple arrays. Such an array will contain one element for each value from the original string. This is easy to achieve in C# and the .NET framework using the Split method of the String class.
String.Split Method
The Split method requires a single parameter containing an array of characters. Each item in the array will be matched to the string being processed as a delimiting character. Handily, the method's parameter is a Parameter Array. This means that multiple characters can be included directly in the method without initialising the array beforehand.
The following code shows how to split 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
*/
|