﻿using System;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// This is original code that implements a word-count algorithm
/// that yields very similar results to Microsoft Word.
/// </summary>
static class WordCount
{
    /// <summary>
    /// Count words (using spaces and character analysis).
    /// </summary>
    /// <param name="str">The string to count the words of.</param>
    /// <returns>The number of words in the document.</returns>
    static public int Count(string str)
    {
        int c = 0;
        for (int i = 1; i < str.Length; i++)
        {
            if (char.IsWhiteSpace(str[i - 1]) == true)
            {
                if (char.IsLetterOrDigit(str[i]) == true ||
                    char.IsPunctuation(str[i]))
                {
                    c++;
                }
            }
            else if (i >= 3 &&
                char.IsLetterOrDigit(str[i]) &&
                char.IsPunctuation(str[i - 1]) &&
                char.IsPunctuation(str[i - 2]) &&
                char.IsLetterOrDigit(str[i - 3]))
            {
                c++;
            }
        }
        if (str.Length > 2)
        {
            c++;
        }
        return c;
    }

    /// <summary>
    /// Count the number of words in the string using regular expression.
    /// </summary>
    /// <param name="textIn">The string you want a word count of.</param>
    /// <returns>The number of words in the string.</returns>
    static public int CountRegex(string textIn)
    {
        MatchCollection collection = Regex.Matches(textIn, @"[\S]+"); 
        return collection.Count;
    }
}
