I am writing a text editor and need to provide a live word count. Right now I am using this extension method:
public static int WordCount(this string s)
{
s = s.TrimEnd();
if (String.IsNullOrEmpty(s)) return 0;
int count = 0;
bool lastWasWordChar = false;
foreach (char c in s)
{
if (Char.IsLetterOrDigit(c) || c == '_' || c == '\'' || c == '-')
{
lastWasWordChar = true;
continue;
}
if (lastWasWordChar)
{
lastWasWordChar = false;
count++;
}
}
if (!lastWasWordChar) count--;
return count + 1;
}
I have it set so that the word count runs on the richtextbox's text every tenth of a second (if the selection start is different from what it was last time the method ran). The problem is that the word count gets slow when working on very long files. To solve this I am thinking about having the word count only run on the current paragraph, recording the word count each time and comparing it against what the word count was last time the word count ran. It would then add the difference between the two to the total word count. Doing this would cause many complications (if the user pastes, if the user deletes a paragraph, ect.) Is this a logical way to go about improving my word count? Or is there something that I don't know about which would make it better?
EDIT: Would it work to run the word count on a different thread? I don't know much about threading, will research.
SAMPLE TEXT THAT I USED: