WordCount

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

Description

Count all words in a given string. Excludes whitespaces, tabs and line breaks.

Details

Double click on the code to select all.

 

;