WordCount
Count all words in a given string. Excludes whitespaces, tabs and line breaks.
Source
using System.Text.RegularExpressions;
public class MyExtension
{
/// <summary>
/// Count all words in a given string
/// </summary>
/// <param name="input">string to begin with</param>
/// <returns>int</returns>
public static int WordCount(this string input)
{
var count = 0;
try
{
// Exclude whitespaces, Tabs and line breaks
var re = new Regex(@"[^\s]+");
var matches = re.Matches(input);
count = matches.Count;
}
catch
{
}
return count;
}
}
Example
string word = "the quick brown\r\nfox jumps over the lazy \tdog.";
Console.WriteLine("Total Words: {0}", word.WordCount());
// returns 9