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
Post a Comment