
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
70
|
Chapter 2: Strings and Characters
In addition to the Append method, you should also wrap any AppendFormat, Insert,
and
Replace methods of the StringBuilder object in a try-catch block. Any of these
methods can allow characters to be added to the
StringBuilder string, potentially
causing its length to exceed its maximum specified length.
See Also
See the “StringBuilder.Append Method” topic in the MSDN documentation.
2.20 Iterating over Each Character in a String
Problem
You need to iterate over each character in a string efficiently in order to examine or
process each character.
Solution
C# provides two methods for iterating strings. The first is the foreach loop, which
can be used as follows:
string testStr = "abc123";
foreach (char c in testStr)
{
Console.WriteLine(c.ToString( ));
}
This method is quick and easy. Unfortunately, it is somewhat less flexible than the
second method, which uses the
for loop instead of a foreach loop to iterate over the
string. For example:
string testStr = "abc123";
for (int counter = 0; counter < testStr.Length; counter++)
{
Console.WriteLine(testStr[counter]);
}
Discussion
The foreach loop is simpler and thus less error-prone, but it lacks flexibility. In con-
trast, the
for loop is slightly more complex, but it makes up for that in flexibility.
The
for loop method ...