c# - Counting the Words in a String from a file -


i have small console application working on, , returns several 0's instead of actual count of words. have noticed in regards logic flawed since counting spaces. not count last word in string. suggestions on how fix 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 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 not exist, creating it");             file.create(file);         }          console.readline();     } 

i have edited checking contents instead of file path (noob here making noob mistakes). still feel though logic if statement inside of foreach loop bad though.

        if (fileexists)         {             console.writeline("{0} contains following", file);             string[] contents = file.readalllines(file);              foreach (string words in contents)             {                 int stringcount = 0;                 if (words == " ")                 {                     stringcount++;                 }                 console.writeline(stringcount);             }          } 

string.split , file.readalltext function should at.

var count = file.readalltext(file).split(' ').count(); 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -