Practice Exercises C# Sharp - Learn to program with performing exercises C# Sharp

Practice Exercises C# Sharp

Learn to program with performing exercises C# Sharp


Count letters in file - Practice Exercises C# Sharp


Lesson 8:

File management


Exercise 8.8:

Count letters in file


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)


Source 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();
        }
    }
}
Exercisey 8.8




Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.