Assume that each word is separated by a space.
Examples:
Input: How is you!
Output: 3
Two methods:
One:
#include <stdio.h> #include <string.h> #define SIZE 20int Main () {char str[size]={'};int ' count=0;printf (" Please input the string\n "); gets (str);p UTS (str), int length = strlen (str); for (int i=0;i<length;i++) {// Infer whether the space is not a word in the while inside i++ run inference to the next space appears or End if (str[i]!= ") {count++;while (str[i]!= ' &&str[i]!= ') {i++;}}} printf ("%d\n", count); return 0;}
Another type of:
#include <stdio.h> #include <string.h> #define SIZE 20int Main () {char str[size]={'};int ' Count=0;int flag= 0;printf ("Please input the string\n"), gets (str);p UTS (str), int length = strlen (str); for (int i=0;i<length;i++) {// Inference is not a space. If that's the case, flag=0,//is not. Infer whether the front is a space or flag equals 0. is a space if the new word starts if (str[i]== ') {flag=0;} Else{if (flag==0) {count++;flag=1;}}} printf ("%d\n", count); return 0;}
The C language counts the number of words in a string