统计单词数目的三种解法

 1 #include<cstdio>
 2 using namespace std;
 3 int main()
 4 {
 5     char s[101];
 6     int n = 1, count = 0;
 7     gets(s);
 8     for(int i = 0; i <= 100; i++)
 9     {
10         if(s[i] == '') break;
11         if(s[i] == ' ') n = 1;
12         else
13         {
14             if(n == 1)
15             {
16                 n = 0;
17                 count++;
18             }
19         }
20     }
21     printf("%d", count);
22     return 0;
23 }

比较麻烦,emmm...但比较好理解

就是先扫一遍,判断

然后因为开头单词前面没有空格,所以要单独判断。。。

#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    char s[101];
    int n = 1, count = 0;
    gets(s + 1);
    s[0] = ' ';//预处理,前面加空格。 
    for(int i=0; i<=100; i++)
    {
        if(s[i] != ' ' && s[i-1] == ' ')
        count++;//计数 
    }
    printf("%d", count);
    return 0;
}

嗯。。。更简单了,但比较难想到

先做一下预处理,在整个字符串前面加一个空格

这样,之后就可以愉快的累加啦/手动滑稽/

#include<cstdio>
#include<cstring>
using namespace std;
char s[101];
char x[105][1005];
char tmp[105];
int main()
{
    char *p = s;
    gets(s);
    int i = 0, count = 0;
    while(++i)
    {
        while(p[0] == ' ') p+=1;
        if(sscanf(p,"%s", x[i]) == -1) break;
        sprintf(tmp, "%s", x[i]);
        p += strlen(tmp);
        count++;
    }
    printf("%d", count);
    return 0;
}

可爱的sscanf和sprintf。。。

详解请参照下一条。。。/233/

原文地址:https://www.cnblogs.com/orange-233/p/11961576.html