Wednesday, April 16, 2008

Split string to array of strings in csharp (c#).

    When we should divide a string to array of strings by a specific delimiters, we can use method String.Splt().

Samples:

string line = "name,id=1234,,description,user=Jon";



string[] lineItems = line.Split(new char[] { ',' });
DisplayOutput(line, lineItems);


splitOutput1



lineItems = line.Split(new char[] { ',', '=' });
DisplayOutput(line, lineItems);



splitOutput2



lineItems = line.Split(new char[] { ',', '=' }, 2);
DisplayOutput(line, lineItems);


splitOutput3



lineItems = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
DisplayOutput(line, lineItems);



splitOutput4



lineItems = line.Split(new string[] { ",", "id=", "user="}, StringSplitOptions.RemoveEmptyEntries);
DisplayOutput(line, lineItems);



splitOutput5



References:



String.Split Method

No comments: