OJ831 统计good及相关题

来源:互联网 发布:程序员能自学吗 编辑:程序博客网 时间:2024/05/01 17:30

统计good
description
我们每天都面临着要学习大量的英文单词,但我最喜欢good这个词,这个词见到的越多,我的生活就越幸福和愉快!给你一些英文单词,你能统计出good有多少个吗?
input
输入数据的第1行一个N (1 < N < 100),代表输入的数据组数,然后有N 行,每行有很多个单词,单词之间用空格隔开;每行的长度不超过100.
output
对于每行数据,输出其中含good单词的个数。
sample_input
2
i am a good boy!
goof good good dood good
sample_output
1
3

#include <iostream>#include <algorithm>#include <stdio.h>#include <string.h>using namespace std;int main(){  char a[100];  char b[100];  int n,k,count,j,i;  while (cin>>n)  {getchar();      while (n--)      {          count=0;          gets(a);          k=strlen(a);          for (i=0;i<k;i++)          {              if (a[i]!=' ')              {                  b[j]=a[i];                  j++;              }              else              {                  b[j]='\0';                  j=0;                  if (strcmp(b,"good")==0)                    count++;              }          }          if (a[k-1]=='d'&&a[k-2]=='o'&&a[k-3]=='o'&&a[k-4]=='g')            count++;          cout<<count<<endl;      }  }    return 0;}

PS:
在输入N之后,必须加上getchar!!!!因为输入N之后回车键进入gets();
但是gets()后面不加getchar!!!这是为什么??

最后的good字符没有了空格,所以要单独讨论。

当B中封上一次边儿之后必须让J回归零!

统计字符串中单词的个数和拆分单词(单词间不仅有一个空格——)

#include <iostream>#include <algorithm>#include <stdio.h>#include <string.h>using namespace std;int main(){  char a[100],b[100][100];  int i,j,m,n,num,k;  int flag;    while (cin>>n)  {      while (n--)      {      getchar();      gets(a);      getchar();      m=strlen(a);      flag=0;j=0;num=0;k=0;      for (i=0;i<m;i++)      {          if (a[i]==' ')          {              if (flag==1)              {                  b[k][j]='\0';                  k++;              }              flag=0;          }          else          {             if (flag==0)             {                 flag=1;                 num++;                 j=0;             }             b[k][j]=a[i];          }      }      b[k][j]='\0';      for (i=0;i<num;i++)        printf ("%s",b[i]);  }    return 0;}}
0 0