✔ 最佳答案
#include < stdio.h >
int count_words(char* str)
{
int i;
bool mode = false;// true - word mode, false - space mode
int cnt = 0;
for (i=0; str[i] != '\0'; i++)
{
switch (str[i])
{
case ' ': case '\n': case '\t':// separator
if (mode)
cnt++;
mode = false;
break;
default:
mode = true;
break;
};
}
if (mode)
cnt++;
return cnt;
}
int main()
{
char* str = "this is line one\nthis is line two";
char str2[] = " this \n\t is another \t \t test \t\t";
printf("# of words in\n[%s] = %d\n", str, count_words(str));
printf("# of words in\n[%s] = %d\n", str2, count_words(str2));
return 0;
}