Saturday, 18 January 2014

Convert Comma-Separated Strings to String Arrays

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


*/

No comments:

Post a Comment

SQL SERVER – Disk Space Monitoring – Detecting Low Disk Space on Server

CREATE PROCEDURE [CSMSDVLP].[DiskSpaceMonitor] @mailProfile nvarchar(500), @mailto nvarchar(4000), @threshold INT, @logfile nvarchar(40...