How to find number of words in a string without using split method


Using string split function:

  1. static void Main(string[] args)
  2.         {
  3.             string str = Console.ReadLine();
  4.             string[] words = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  5.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words.Length);
  6.             Console.Read();
  7.         }

Find number of words without using string.split function:

Using Regex:
  1. static void Main(string[] args)
  2.         {
  3.             string str = Console.ReadLine();
  4.             var words = Regex.Matches(str, @"[\S]+");
  5.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words.Count);
  6.             Console.Read();
  7.         }

Using whitespace:
  1. string str = Console.ReadLine();
  2.             int words = 1;
  3.             for (int i = 0; i < str.Length – 1; i++)
  4.             {
  5.                 if (char.IsWhiteSpace(str[i]) == true)
  6.                 {
  7.                     words++;
  8.                 }
  9.             }
  10.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words);
  11.             Console.Read();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s