Programming Course in C# ¡Free!

Count letters in file

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a program to count the amount of times that a certain character is inside a file (of any kind).

The file and the letter can be asked to the user or passed as parameters:

count example.txt a

It must display in screen the amount of letters found.

(you can choose any way to interact with the user, showing the proper help)



using System;
using System.IO;

class CountLetters
static void Main()
bool debug = true;

Console.Write("Name of file: ");
string nameFile = Console.ReadLine();

Console.Write("Letter for count: ");
string letter = Console.ReadLine();

StreamReader myfile;
myfile = File.OpenText( nameFile );

string line;
int countLetter =0;
line = myfile.ReadLine();
if (line != null)
for (int i=0; i < line.Length; i++)
if (line.Substring(i,1) == letter)
while (line != null);

Console.WriteLine("Amount of letter: {0}",countLetter);

if (debug)