Exercise
Count words
Objetive
Create a C# program to count the amount of words stored in a text file
Example Code
// Import the System namespace for basic functionality
using System;
// Import the IO namespace for file handling
using System.IO;
// Create the class to count words in the text file
class WordCounter
{
// Main method where the program starts
static void Main(string[] args)
{
// Ask the user for the path of the text file
Console.WriteLine("Enter the path of the text file:");
// Get the file path from the user
string filePath = Console.ReadLine();
// Start of try block to handle any file or reading errors
try
{
// Read the content of the file
string content = File.ReadAllText(filePath);
// Count the number of words in the file by splitting the content into words
int wordCount = CountWords(content);
// Display the result to the user
Console.WriteLine("The number of words in the file is: " + wordCount);
}
catch (Exception ex) // Catch any exceptions that may occur during file reading
{
// Print the exception message if an error occurs
Console.WriteLine("An error occurred: " + ex.Message);
}
}
// Method to count the number of words in a string
private static int CountWords(string content)
{
// Split the content by spaces, tabs, newlines, etc. to get an array of words
string[] words = content.Split(new char[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
// Return the length of the array, which is the number of words
return words.Length;
}
}