下面的程序先输入一个字符串,以“回车”结束输入,定义一个字符型指针变量p,指向字符串,循环统计字符串中的空格和非空格的数量。我跑过这个程序了,没有错误的。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char str[50];
int i;
char * p;
int num_space;
int num_not_space;
printf("please input a string:\n");
str[0]=getchar();
i=0;
while(str[i]!='\n')
{
i++;
str[i]=getchar();
}
str[i]='\0';
printf("the string is %s\n",str);
p=str;
num_space=0;
num_not_space=0;
for(p;*p!='\0';p++)
{
if(*p==' ')
{
num_space++;
}
else
{
num_not_space++;
}
}
printf("the number of space is %d\n",num_space);
printf("the number of no space is %d\n",num_not_space);
return 0;
}
运行结果如下,也可以自己跑一下程序。
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/2cf5e0fe9925bc316320627e5bdf8db1ca1370d2?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)