Count words in a text (words are only separated by ' ' (spaces)) - CSharp System

CSharp examples for System:String Split

Description

Count words in a text (words are only separated by ' ' (spaces))

Demo Code


using System.Text;
using System.Globalization;
using System.Collections.Specialized;
using System.Collections;
using System;/*w w w  . j a v a 2s  .  c  o  m*/

public class Main{
        /// <summary>
        /// Count words in a text (words are only separated by ' ' (spaces))
        /// </summary>
        static public int CountWords( string text )
        {
            if ( text == null )
                throw new ArgumentNullException( "text",
                    "Unable to execute method without valid text." );

            return text.Split( new char[] { ' ' } ).Length;
        } // CountWords(text)
}

Related Tutorials