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, you 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 is comma-delimited. However, it can be 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[2] {'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.
 |