text file

  • Thread starter Thread starter troy
  • Start date Start date
T

troy

hello,

I'm new at this and need pointers on how I can read a file (text or xml)
from the file system and count the number of words in that file. Any ideas?

thanks
Troy
 
Hi Troy,

I'm sure there is a better way to count the words, but this will work

StreamReader sr = new StreamReader("MyFile");
string data = sr.ReadToEnd();
sr.Close();

string[] words = data.Split(null); // splits at all blank characters

int count = 0;
foreach(string s in words)
{
if((s.Trim()).Length > 0)
count++;
}

count will now be the number of strings of at least 1 character length.
You may want to refine the count and ignore symbols. Regex might be
suitable for this.


Happy coding!
Morten Wennevik [C# MVP]
 
holy that was fast - thanks man...

Hi Troy,

I'm sure there is a better way to count the words, but this will work

StreamReader sr = new StreamReader("MyFile");
string data = sr.ReadToEnd();
sr.Close();

string[] words = data.Split(null); // splits at all blank characters

int count = 0;
foreach(string s in words)
{
if((s.Trim()).Length > 0)
count++;
}

count will now be the number of strings of at least 1 character length.
You may want to refine the count and ignore symbols. Regex might be
suitable for this.


Happy coding!
Morten Wennevik [C# MVP]
 
lol I recomended that to someone else and got chewed a new one...something
about way too much memory usage. If it works....
 
Yep, I suspect it is highly inefficient, but it should work.

Happy coding!
Morten Wennevik [C# MVP]
 
Scatropolis said:
lol I recomended that to someone else and got chewed a new one...something
about way too much memory usage. If it works....

You certainly don't need to read the whole thing in one go. You could
loop round on a line-by-line basis using StreamReader.ReadLine().
 
Back
Top