Count words Learn programming C#

Lesson:

File Management


Exercise:

Count words


Objetive:

Create a C# program to count the amount of words stored in a text file


Code:

using System;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        StreamReader file = File.OpenText("1.cs");
        string line;
        int amountOfWords = 0;
        do
        {
            line = file.ReadLine();
            if (line != null)
            {
                string[] words = line.Split(' ');
                amountOfWords += words.Length;
            }
        }
        while (line != null);
        file.Close();
        Console.WriteLine("Words: " + amountOfWords);
    }
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.