Recipe 2.18 Extracting Items from a Delimited String

Recipe 2.18 Extracting Items from a Delimited String

Problem

You have a string, possibly from a text file, which is delimited by one or more characters . You need to retrieve each piece of delimited information as easily as possible.

Solution

Using the Split instance method on the string class, we can place the delimited information into an array in as little as a single line of code. For example:

 string delimitedInfo = "100,200,400,3,67"; string[] discreteInfo = delimitedInfo.Split(new char[1] {','}); foreach (string Data in discreteInfo)     Console.WriteLine(Data); 

The string array discreteInfo holds the following values:

 100 200 400 3 67 

Discussion

The Split method, like most methods in the string class, is simple to use. This method returns a string array with each element containing one discrete piece of the delimited text split on the delimiting character(s).

In the Solution, the string delimitedInfo was comma-delimited. However, it could have been delimited by any type of character or even by more than one character. When there is more than one type of delimiter , use code like the following:

 string[] discreteInfo = delimitedInfo.Split(new char[3] {',', ':', ' '}); 

This line splits the delimitedInfo string whenever one of the three delimiting characters (comma, colon , or space character) is found.

The Split method is case-sensitive. To split a string on the letter " a " in a case-insensitive manner, use code like the following:

 string[] discreteInfo = delimitedInfo.Split(new char[1] {'a', 'A'}); 

Now, anytime the letter " a " is encountered , no matter what its case, the Split method views that character as a delimiter.

See Also

See the "String.Join Method" topic in the MSDN documentation.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net