- Course
- Text Files B
- Count the words in a file
Count the words in a file
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a program in C# to count the number of words stored in a text file.
Input
Output
404
Solution
using System;
using System.IO;
public class CountWordsInFile
{
public static void Main(string[] args)
{
string fileName = "input.txt";
string line;
int wordsCount = 0;
using (StreamReader file = File.OpenText(fileName))
{
do
{
line = file.ReadLine();
if (line != null)
{
wordsCount += line.Split(' ').Length;
}
}
while (line != null);
}
Console.WriteLine(wordsCount);
}
}