
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Counting Lines of Text
|
579
The following method counts the lines within a specified text file and a specified
string:
public static void TestLineCount( )
{
// Count the lines within the file TestFile.txt.
LineCount(@"C:\TestFile.txt", true);
// Count the lines within a string.
// Notice that the \r\n characters start a new line
// as well as just the \n character.
LineCount("Line1\r\nLine2\r\nLine3\nLine4", false);
}
Discussion
Every line ends with a special character. For Windows files, the line-terminating
characters are a carriage return followed by a line-feed. This sequence of characters is
described by the regular expression pattern
\r\n. Unix files terminate their lines with
just the line-feed character (
\n). The regular expression "\n" is the lowest common
denominator for both sets of line-terminating characters. Consequently, this method
runs a regular expression that looks for the pattern
"\n" in a string or file.
Macintosh files usually end with a carriage-return character (\r). To
count the number of lines in this type of file, the regular expression
should be changed to the following in the constructor of the
Regex
object:
Regex RE = new Regex("\r", RegexOptions.Multiline);
}
return (numOfLines);
}
else
{
Regex RE = new Regex("\n", RegexOptions.Multiline);
MatchCollection theMatches ...