函数delspace的功能是删除一个字符串中所有的空格。例如,输入字符串为"This is a string",

函数delspace的功能是删除一个字符串中所有的空格。例如,输入字符串为"This is a string",则输出结果为"Thisisastring"。测试用主函数如下所示,请编制函数delspace。
#include <stdio.h>
#include <string.h>
void main()
{ char *delspace(char *str);
char s[81],*ds;
gets(s);
ds=delspace(s);
printf("\nResult: %s\n", ds);
}
char *delspace(char *str)
{
char *p=str;
while(*p)
{
if(*p==' ')
strcpy(p,p+1);
else
p++;
}

return str;
}
我的疑问是为什么少了while(*p),程序执行只是照原样输出。

大哥,虽然无意中翻到你的问题 但是你函数里面
if(*p==' ')
strcpy(p,p+1);
else
p++;
也就是说 如果p == ' ' 你就把P+1的值拷到p这里,但是拷完了P的位置还是原位置啊,然后下一个循环里 万一刚才P+1的值也是 ' ' 呢你不就死循环了啊。
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-12-16
while(*p)是在从头到尾查找串里的每个字符
没有它只检查了串里第一个字符本回答被提问者采纳