Counting words in a string - c programming

You needed

int words(const char sentence[])
{
}

(note braces).

For loops go with ; instead of ,.


Without any disclaimer, here's what I'd have written:

See it live http://ideone.com/uNgPL

#include <string.h>
#include <stdio.h>

int words(const char sentence[ ])
{
    int counted = 0; // result

    // state:
    const char* it = sentence;
    int inword = 0;

    do switch(*it) {
        case '\0': 
        case ' ': case '\t': case '\n': case '\r': // TODO others?
            if (inword) { inword = 0; counted++; }
            break;
        default: inword = 1;
    } while(*it++);

    return counted;
}

int main(int argc, const char *argv[])
{
    printf("%d\n", words(""));
    printf("%d\n", words("\t"));
    printf("%d\n", words("   a      castle     "));
    printf("%d\n", words("my world is a castle"));
}

See the following example, you can follow the approach : count the whitespace between words .

int words(const char *sentence)
{
    int count=0,i,len;
    char lastC;
    len=strlen(sentence);
    if(len > 0)
    {
        lastC = sentence[0];
    }
    for(i=0; i<=len; i++)
    {
        if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ')
        {
            count++;
        }
        lastC = sentence[i];
    }
    return count;
}

To test :

int main() 
{ 
    char str[30] = "a posse ad esse";
    printf("Words = %i\n", words(str));
}

Output :

Words = 4

#include <ctype.h> // isspace()

int
nwords(const char *s) {
  if (!s) return -1;

  int n = 0;
  int inword = 0;
  for ( ; *s; ++s) {
    if (!isspace(*s)) {
      if (inword == 0) { // begin word
        inword = 1;
        ++n;
      }
    }
    else if (inword) { // end word
      inword = 0;
    }
  }
  return n;
}

Tags:

C

String

Function