
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
48
|
Chapter 2: Strings and Characters
The Split method may also be used to separate people’s first, middle, and last
names. For example:
string fullName1 = "John Doe";
string fullName2 = "Doe, John";
string fullName3 = "John Q. Doe";
string[] nameTokens1 = fullName1.Split(new char[3]{' ', ',', '.'});
string[] nameTokens2 = fullName2.Split(new char[3]{' ', ',', '.'});
string[] nameTokens3 = fullName3.Split(new char[3]{' ', ',', '.'});
foreach (string tok in nameTokens1)
{
Console.WriteLine(tok);
}
Console.WriteLine("");
foreach (string tok in nameTokens2)
{
Console.WriteLine(tok);
}
Console.WriteLine("");
foreach (string tok in nameTokens3)
{
Console.WriteLine(tok);
}
This code produces the following output:
John
Doe
Doe
John
John
Q
Doe
Notice that a blank is inserted between the period and the space delimiters of the
fullName3 name; this is correct behavior. If you do not want to process this space in
your code, you can choose to ignore it.
Discussion
If you have a consistent string with parts, or tokens, that are separated by well-
defined characters, the
Split function can tokenize the string. Tokenizing a string
consists of breaking the string down into well-defined, discrete parts, each of which
is considered a token. In the two previous examples, the tokens were either parts of a
mathematical equation ...