I also use a Regex expression to count words, which returns the same number of words as MS Word. I wrap the Regular Expression in a String
extension method to make it easy to use.
public static class StringExtensions
{
private const string WordCountRegex = @"[^\s!?¡¿\-\–]+";
private static Regex regexWordCounts = new Regex(WordCountRegex,
RegexOptions.Compiled | RegexOptions.Multiline);
public static int WordCounts(this string sentence)
{
try
{
MatchCollection matchCollection = regexWordCounts.Matches(sentence);
return matchCollection.Count;
}
catch
{
return 0;
}
}
}
Taking the samples above, this would give the following:
string input =
"The total number of words \t this sentence is 10.";
int wordCounts = input.WordCounts();
input = "Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99";
int wordCounts = input.WordCounts();
Hope this helps.