Simple, Quality, Awesome Software

Sentence and Paragraph Count

Below is the complete code for the Sentence and Paragraph Count Try It Out! problem.

The StringExtensions Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethods
{
    /// <summary>
    /// A place to put extension methods for the string type.
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// Counts the number of words in a string and returns it.
        /// </summary>
        public static int WordCount(this string text)
        {
            return text.Split(' ').Length;
        }

        /// <summary>
        /// Counts the number of sentences in a string. Note that this
        /// is definitely an oversimplification, as there are other uses
        /// for the '.' character than ending sentences. This method
        /// ignores ellipses that are represented as "...".
        /// </summary>
        public static int SentenceCount(this string text)
        {
            text = text.Replace("...", "");
            return text.Split('.').Length;
        }

        /// <summary>
        /// Counts the number of paragraphs in a string. Paragraphs
        /// are assumed to be delimited by the new line character
        /// ('\n').
        /// </summary>
        public static int ParagraphCount(this string text)
        {
            return text.Split('\n').Length;
        }
    }
}

The Program Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string allText = File.ReadAllText("lorem ipsum.txt");
            Console.WriteLine("Words: " + allText.WordCount());
            Console.WriteLine("Sentences: " + allText.SentenceCount());
            Console.WriteLine("Paragraphs: " + allText.ParagraphCount());

            Console.ReadKey();
        }
    }
}