题目:
7-3 统计字符串中空格数
分数 20
全屏浏览题目
切换布局
作者 庄波
单位 滨州学院
输入一个字符串,统计其空格的数量。
要求编写函数
int count_sp(const char *s);
统计并返回字符串 s 中空格的数量。
输入格式:
在一行中输入一个长度不超过 80 的字符串,其中可能含有多个空格。
输出格式:
输出共 2 行:第一行打印输入的原字符串,第二行是该字符串中空格的数量。
输入样例:
在这里给出一组输入。例如:
Hello world
输出样例:
在这里给出相应的输出。例如:
Hello world
1
程序样例
#include<stdio.h> #define STRLEN 80 // 返回字符串 s 中空格的数量 int count_sp(const char *s); int main (void) { char s[STRLEN + 1]; // 输入字符串 gets(s); // 输出字符串及其空格数 printf("%s\n%d\n", s, count_sp(s)); return 0; } /*** 在此实现 count_sp 函数 ***/
答案:
#include <string.h>
#include<stdio.h>
#define STRLEN 80
// 返回字符串 s 中空格的数量
int count_sp(const char *s);
int main (void)
{
char s[STRLEN + 1];
// 输入字符串
gets(s);
// 输出字符串及其空格数
printf("%s\n%d\n", s, count_sp(s));
return 0;
}
int count_sp(const char *s)//我这儿是编程题,如果是函数题可以把上面的删掉
{
int i=0,j=0;
for(i=0,j=0;*s!='\0';i++,s++)
if(*s==' ')j++;
return j;
}