Thursday, December 8, 2011

Counting Words in a String using C

Counting words in a String using C:
This is very good exercise to test new programmers pointer skills. The task is to count the words in a given string using C. Well there might be many ways you can do it, I will demonstrate mine way.
Note that mine solution might not be the optimal one, but it gets the job done.

Logic:
How to calculate words in a given string using C. Well I generally use two pointers, one pointer pointers to first char of the string, second point to next char. Then we compare the content on the two pointers. There will be 3 cases:
  1. Both pointers are blank chars (space), so that means we are in between words
  2. First pointer is blank, other is not. This is denote beginning of the Word.
  3. Rest cases will be when either in the middle of the words or at the ending of the words.
Check this image for clarity.

The two Orange dots represent the two pointers in the middle of words.
The two Green dots represent when first char is blank and other is not. this marks the beginning of the word and here we count the word.
The two red dots represent the case when pointers are in the middle of the words, we don't do anything.
Why are we using 2 pointers?
This will allow our function to count the words that are separated by more then one space (which is very handy, when user puts too many spaces in the string)

Code:


#include<stdio.h>
#include<conio.h>
#include<string.h>// for strlen function

int countWord(const char* str)
{
    int c=0,l,i;
    char* p1;//first pointer
    char* p2;//second pointer
    p1=str;//assing first pointer to first char of string
    p2=p1+1;//assign 2nd pointer to next of first
    l=strlen(str);
    printf("\n String has  %d length",l);
    
    
    if(p1==NULL)
    {
        return(0);
    }
    else
    {
        //check if first char is space or not, if not then its the first word
        if(*p1!=' ')
        {
            c=1;
        }
    }
    
    for(i=0;i<l;i++)
    {
        
        if((*p1==' ')&&(*p2==' '))
        {
            //both p1 and p2 are blank , so do nothing
        }
        else if((*p1==' ') && (*p2!=' '))
        {
            //first pointer is blank but second is not, means a word is there
            c++;    
        }
        else
        {
            // rest dont need to worry
            
        }
        //increment both pointers
        p1++;
        p2++;
    }
    
    
    return(c);
}

int main()
{
    char *name;
    printf("\n Enter a string= ");
    gets(name);
    printf("%s",name);
    printf("number of words=%d",countWord(name));
}