P085 删除字符串中的所有空格 ★★

03-程序设计题 软件121, 唐鼎威 1972浏览

所属年份:2010.9;2011.3;2011.9;
请编写一个函数,用来删除字符串中的所有空格。
例如,输入asd af aa z67,则输出为asdafaaz67。

#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <stdlib.h>
void fun (char *str)
{
  
}
main()
{
  char str[81];
  char Msg[]="Input a string:";
  int n;
  FILE *out;
  printf(Msg);
  gets(str);
  puts(str);
  fun(str); 
  printf("*** str: %s\n",str); 
  /******************************/
  out=fopen("out.dat","w");
  fun(Msg);
  fprintf(out,"%s",Msg);
  fclose(out);
  /******************************/
}

【解题思路】
本题要求删除所有空格,即保留除了空格以外的其他所有字符。由于C语言中没有直接删除字符的操作,所以对不需要删除的字符采用”保留”的操作。用指针p指向字符串中的每一个字符,每指向到一个字符都判断其是否为空格,若不是空格则保存到str[i]。
【参考答案】

void fun (char *str)
{
   int i=0;
   char *p=str;
   while(*p)
   {
      if(*p!=' ')          /*删除空格*/
      {
         str[i]=*p;
         i++;
      }
      p++;
   }
   str[i]='\0';            /*加上结束符*/
}