/*指针去除字符串空格*/
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[]="i apple tr ee";
char *q,*p;
p=q=str;
while(*p!='\0')
{
if(*p!=' '){
*q++=*p++;
}
else{
p++;
}
}
*q='\0';
printf("%s\n", q);
printf("%s\n", str);
return 0;
}
//这种malloc申请空间方法不太建议
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[]="i apple tr ee";
char *p=str,*q=(char *)malloc(sizeof(str));
int i=0;
while(*p!='\0')
{
if(*p!=' '){
*(q+i)=*p;i++;
//使用q+i,那q也是不会变的,所以后面输出可以用q
}p++;
}
*(q+i)='\0';
printf("%s\n", q);
free(q);
return 0;
}
/*通过数组去除*/
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
int i,j=0;
gets(str);
for(i=0;i<strlen(str);i++)
if(str[i]!=' ') str[j++]=str[i];
str[j]='\0';
//puts(str);
printf("%s\n",str);
return 0;
}
//尽量写模块函数的方法。
#include <stdio.h>
#define LEN 81
int drop_space(char * s);
int main(void)
{
char orig[LEN];
while (gets(orig) && orig[0] != '\0')
{
drop_space(orig);
puts(orig);
}
puts("Bye!");
return 0;
}
int drop_space(char * s)
{
char *p, *q;
p=q=s;
while ( *q != '\0' )
{
if ( *q != ' ')
{
*p++ = *q++;
}
else
{
q++;
}
}
*p = '\0';
}