C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: It does this by using the parameterless ReadLine instance method offered by the StreamReader class in the System.IO namespace.
CountLinesInFile: This method is static because it stores no state. It contains the logic for counting lines in a file.
StaticAnd: It uses StreamReader, which is a useful class for reading in files quickly. It has the useful ReadLine method.
Next: It increments the count, which contains the number of lines in the file. Finally the int containing the count is returned.
C# program that counts file lines
using System.IO;
class Program
{
static void Main()
{
CountLinesInFile("test.txt");
}
/// <summary>
/// Count the number of lines in the file specified.
/// </summary>
/// <param name="f">The filename to count lines.</param>
/// <returns>The number of lines in the file.</returns>
static long CountLinesInFile(string f)
{
long count = 0;
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
}
return count;
}
}
Output
(Number of lines in text.txt)
First method: The first method uses IndexOf. It finds all the newline characters.
Second method: The second method uses MatchCollection. This method uses the Matches method with RegexOptions.Multiline.
IndexOfC# program that counts lines in string
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
long a = CountLinesInString("This is an\r\nawesome website.");
Console.WriteLine(a);
long b = CountLinesInStringSlow("This is an awesome\r\nwebsite.\r\nYeah.");
Console.WriteLine(b);
}
static long CountLinesInString(string s)
{
long count = 1;
int start = 0;
while ((start = s.IndexOf('\n', start)) != -1)
{
count++;
start++;
}
return count;
}
static long CountLinesInStringSlow(string s)
{
Regex r = new Regex("\n", RegexOptions.Multiline);
MatchCollection mc = r.Matches(s);
return mc.Count + 1;
}
}
Output
2
3
So: Generally there is no advantage to the regular expression library when doing simple operations such as this.
Benchmark results for line counting:
Version A - Count: 188 ms [faster]
Version B - Regex: 5959 ms