Counting the Words in a String from a file
I have a small console application that I am working on, and it returns
several 0's instead of the actual count of words. I have also noticed in
some regards that my logic will be flawed since I am counting spaces. This
will not usually count the last word in the string. Any suggestions on how
to fix my code. Thanks.
static void Main()
{
bool fileExists = false;
string filePath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = filePath + @"\wordcount.txt";
fileExists = File.Exists(file);
if (fileExists)
{
Console.WriteLine("{0} contains the following", file);
Console.WriteLine(File.ReadAllLines(file));
foreach (char words in file)
{
int stringCount = 0;
if (words == ' ')
{
stringCount++;
}
Console.WriteLine(stringCount);
}
}
else
{
Console.WriteLine("The file does not exist, creating it");
File.Create(file);
}
Console.ReadLine();
}
I have edited it so that I am checking the contents instead of the file
path (noob here making noob mistakes). I still feel as though my logic
with the if statement inside of the foreach loop is bad though.
if (fileExists) { Console.WriteLine("{0} contains the following", file);
string[] contents = File.ReadAllLines(file);
foreach (string words in contents)
{
int stringCount = 0;
if (words == " ")
{
stringCount++;
}
Console.WriteLine(stringCount);
}
}
No comments:
Post a Comment