Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting words in a string - c programming

Tags:

c

function

string

I need to write a function that will count words in a string. For the purpose of this assignment, a "word" is defined to be a sequence of non-null, non-whitespace characters, separated from other words by whitespace.

This is what I have so far:

int words(const char sentence[ ]);

int i, length=0, count=0, last=0;
length= strlen(sentence);

for (i=0, i<length, i++)
 if (sentence[i] != ' ')
     if (last=0)
        count++;
     else
        last=1;
 else
     last=0;

return count;

I am not sure if it works or not because I can't test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?

like image 357
PhillToronto Avatar asked Oct 02 '12 21:10

PhillToronto


1 Answers

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"));
}
like image 138
sehe Avatar answered Sep 23 '22 06:09

sehe