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'}); ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.