输入一个字符串,统计出其中空格的个数 C语言

如题所述

思路:统计字符串中的空格,所以该字符串中有空格,则输入只能使用gets函数,再依次遍历该字符串,判断字符是否是空格,如果是,则空格个数自加1。

参考代码:

#include<string.h>
#include<stdio.h>
#include<math.h>
int main()
{
int sum=0,i;
char a[100];
gets(a);
for(i=0;a[i]!='\0';i++)
if(a[i]==' ')
sum++;
printf("%d\n",sum);
return 0;
}
/*
输出: 
af  adf  asfd
4
*/
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-01
#include <stdio.h>
void main()
{
char c;
int space=0;
printf("输入一个字符串:\n");
while((c=getchar())!='\n')
{
if(c==' ')
space++;
}
printf("空格个数:%d\n",space);
getchar();
}
第2个回答  推荐于2017-09-23
#include <stdio.h>
int main()
{
char s[1000];
int count = 0;
int i;
gets(s);
for(i=0; i<1000 && s[i]!='\0'; i++)
if(s[i] == ' ') count++;
printf("空格个数:%d\n", count);
system("pause");
return 0;
}本回答被提问者采纳
第3个回答  2021-01-11

C语言字符串的学习,输入指定字符串,并且计算字符串的位数

第4个回答  2012-04-30
#include <stdio.h>
#include <string.h>

int main()
{
char s[1000];
int len,c,i;
while(gets(s))
{
len = strlen(s);
c = 0;
for(i=0;i<len;i++)
{
if(s[i]==' ')
c++;
}
printf("Space: %d\n",c);
}
}
相似回答