在主函数中输入一个字符串,然后删除该字符串里面所有的空格,并打印删除空格后的字符串。(用指针)

如题所述

#include <stdio.h>

#define INIT_SIZE 20

#define INCR_SIZE 10

void PrintStr(char * str) // 打印字符串

{

char * t;

for (t=str;*t!='\0';t++){

printf("%c",*t);

}

printf("\n");

}

unsigned int StrLen(char *str) /// 求出字符串中含有的字符个数,不包括结束标志 

{                                                      ///  * 这里我没有用库函数求长度,我不知道怎么用

unsigned int i;

for (i=0; str[i++]!='\0';);

return (i - 1);

}

void DeleteSpace(char ** t) //注意函数的参数是指针的指针

{

int i,j,len;

char * s;

char * str = *t;

len = StrLen(str) + 1;

s = (char *)malloc(len);

for (i = 0,j = 0; str[i] != '\0'; i++)

{

if (str[i] != ' ') {

s[j] = str[i];

j++;

}

}

s[j] = '\0';

free(*t); ///释放原有字符串的申请的空间

*t = s; ///原有字符串重新指向

}

void main()

{

char * str = (char *) malloc (INIT_SIZE * sizeof(char));

char ch;

int i = 0; //字符串当前字符数

int len = INIT_SIZE; //字符串空间大小

while (ch = getchar()) { // 循环录入字符串

if (ch == '\n') { ///如果按回车键,则结束

str[i] = '\0'; ///字符串结束标志

break;

}

if (i < len-1) {

str[i] = ch;

} else {

str = (char *) realloc (str, (len + INCR_SIZE) * sizeof(char)); //增加存储空间

str[i] = ch;

len += INCR_SIZE; //重新记录字符串空间

}

i++;

}

DeleteSpace(&str); /// 开删

printf("-----------\n"); /// 华丽的分割线

PrintStr(str);

        free(str);   //释放内存

        str = 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-18
#include <stdio.h>
#include <stdlib.h>#define MAXLENGTH 10 //这里请自己改成100就可以了,我测试只用10!void Output(char *point)
{
char tempstring[MAXLENGTH];
char *tp=tempstring; for(;(*point)!='\0';++point)
{
if(*point!=' ')
{
*tp=*point;
++tp;
}
}
*tp='\0'; printf("去除空格之后:\n");
printf("%s",tempstring);
}
int main()
{
char string[MAXLENGTH];
printf("输入带空格的字符串:\n");
gets(string);
Output(string);
system("pause");
}
第2个回答  2013-07-18
#include <stdio.h>
#include <string.h>char *delchar(char *s, char c_h) {
char *p,*q;
p = s;
while(*p != '\0') {
if(*p == c_h) {
q = p;
while(*q != '\0') {
*q = *(q + 1);
q++;
}
p--;
}
p++;
}
return (s);
}int main() {
char s[80];
char *p,c = ' ';
printf("源串是 : ");
gets(s);
p = delchar(s,c);
printf("去除(%c)后是:%s\n",c,p);
return 0;
}本回答被网友采纳
相似回答