【NOIP2018 普及组 】标题统计

法一用gets读入,因为gets可以读入任何字符且包括空格,直到 ‘\n 换行停止。注意:判断空格时用 ‘ ’

code:

#include<bits/stdc++.h>
using namespace std;
int p,len=0,i,ans;
char a[1212];
int main()
{
gets(a);
len=strlen(a);
for(int i=0;i<len;i++)
if(a[i]==' ')
ans++;
//cout<<ans<<endl;
cout<<len-ans<<endl;
}

法二:用getchar读入,getchar也可以读入任何字符且包括空格其余同上但是getchar为字符中最高效的,gets易导致堆栈溢出 , getchar读入时要手动在末尾加入

 空格 ‘\0’ ,其余读入法均自带。

code:

#include<bits/stdc++.h>
using namespace std;
int p,len=0,i;
char a[1212];
int main()
{
i=0;
while((a[i]=getchar())!='\n')
{
i++;
}
a[i]='\0';
i=0;
while(a[i]!='\0')
{
// putchar(a[i]);

i++;
if(a[i]==' ')
len++;
}
if(a[0]==' ')  必须要特判第一位的空格,因为我在while中 i++ 在 if(a[i]==' ') 前面
len++;
//putchar('\n');
cout<<i-len<<endl;
//cout<<len<<endl;
}

猜你喜欢

转载自www.cnblogs.com/nlyzl/p/11264623.html