Programming Course in C# ¡Free!

Count words

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

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

Output



Solution


using System;
using System.IO;

class CountWords
{
static void Main()
{
StreamReader file = File.OpenText("text.dat");

string line;
int amount = 0;
do
{
line = file.ReadLine();
if (line != null)
{
string[] words = line.Split(' ');
amount += words.Length;
}
}
while(line != null);

file.Close();

Console.WriteLine("Count of words is: " + amount);
}
}