Count letters in a file Learn programming C# Sharp

Lesson:

File Management


Exercise:

Count letters in a file 15


Objetive:

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)


Code:

using System;
using System.IO;
namespace ConsoleApplication1
{
    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;
            do
            {
                line = myfile.ReadLine();
                if (line != null)
                    for (int i = 0; i < line.Length; i++)
                        if (line.Substring(i, 1) == letter)
                            countLetter++;
            }
            while (line != null);
            myfile.Close();

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

            if (debug)
                Console.ReadLine();
        }
    }
}