Search This Blog

Tuesday 9 June 2015

How to Count Words From a String

Counting Words From a String

Two Cases:

case no.1

If there is a single space between every words,like,
Have a nice day.
Then first you have to count the spaces,then the number of the words will be <number of spaces+1>.
In the above example we can see that there is 3 spaces .So the number of words is 3+1=4.

So the code will be in C,

#include<stdio.h>
#include<string.h>
 
int main(void){
   int i,l,count;
   char str[150];

   gets(str);
   count=0;
   l=strlen(str);
   for(i=0;i<=l;i++){
            if(str[i]==' ')count++;
          }
   printf("The number of Words: %d\n",count);
   return 0;
}

case no.2

But what if the sentence is,
Have  .. a nice   day.

here there is 7 spaces and 2 fullstops in the middle of the words.Here we can not apply the previous formula.
Here,There are some steps to count the words.Well,In most programming contest,you will find these types of sentences to calculate words.

Steps are:

1>> First find the start of a word by a loop and if case.
2>>then went on by i++ to find the last of that word.
3>>then continue the loop till the end of the string.

Here is a C code for better understanding the steps.

#include<stdio.h>

#include<string.h>

 int main(void)
    {
   int i,l,count;

   char str[150];   
//variables

   gets(str);

   count=0;      /
/the variable for counting the words

   l=strlen(str);

   for(i=0;i<=l;i++)
    {
      if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
                    //conditions if the ith member of the string is an alphabet(step1)
             {
            count++;

     while((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
                    {
             i++;        
//conditions for finding the last of the word(step 2)
                     }
             }
   }

   printf("The number of Words: %d\n",count);

   return 0;

   }

 if you have any question you can comment.Thank you.

1 comment:

  1. Thank you so much sister!!
    amazing!!
    love for you <3

    ReplyDelete