- 实例要求:
- 给定任意的字符串,
清除字符串中的空格
,并将其输出; - 实例分析:
- 1、指针函数实现,需要注意
指针函数的返回值是一个指针类型
; - 2、字符类型的数组实现,
循环遍历并赋给新的数组
,输出清除字符串中的空格后新的字符串即可; - 示例代码:
- 一、指针函数:
#include <stdio.h>
char *p = NULL;
char *clear_space(char *s)
{
p = s;
while(*s != '\0')
{
if(*s != ' ')
{
*p++ = *s;
}
s++;
}
*p = '\0';
return p;
}
int main(int argc, char const *argv[])
{
char a[] = "hh j jn lll ";
clear_space(a);
printf("%s\n",a);
return 0;
}
linux@ubuntu:~/work/test1$ gcc t6.c
linux@ubuntu:~/work/test1$ ./a.out
hhjjnlll
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void clear_space(char s[])
{
int len = strlen(s);
char new_s[len];
int i = 0;
for (int j = 0; j < len; j++)
{
if (s[j] != ' ')
{
new_s[i++] = s[j];
}
}
new_s[i] = '\0';
printf("%s\n", new_s);
}
int main(int argc, char const *argv[])
{
char s[] = "abc de fg kk ";
clear_space(s);
return 0;
}
linux@ubuntu:~/work/test1$ gcc t6.c
linux@ubuntu:~/work/test1$ ./a.out
abcdefgkk