Counting words in a string - c programming

后端 未结 12 2166
有刺的猬
有刺的猬 2020-12-07 01:52

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 characte

12条回答
  •  鱼传尺愫
    2020-12-07 02:16

    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
    

提交回复
热议问题