Sponsored Ad

Sunday, March 21, 2010

Calculate Word count in String | Get Number of words in String using C#

This utility helps you to calculate number of words in a given string. This method usage the regular expression to calculate word count.

 

        /// <summary>
        /// Returns word count.
        /// </summary>
        public static int WordCount(string strToCount)
        {
            int words;

            Regex reg = new Regex(@"\w+");

            MatchCollection mc = reg.Matches(strToCount);

            if (mc.Count > 0)
                words = mc.Count;
            else
                words = 0;

            return words;
        }

2 comments:

  1. if i had a string with the text in, how would I incorporate it into this script?

    e.g.

    string Text = "I Want to count this.";

    ReplyDelete
  2. Hi Dan,

    Just call this method and pass input string just by using following script

    int ResultCount = WordCount(Text);

    After executing this line you will have 5 in ResultCount for the given string.

    ReplyDelete

Sponsored Ad

Website Update

Followers