
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
68
|
Chapter 2: Strings and Characters
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 charac-
ters (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'}); ...