如果要把字符数组中的每个空格替换成“%20”,即在字符数组中间加上%20,
则需先定义两个数组 a 和 b ,
a 用来存放原字符,
b 用来存放加完 %20 之后的字符,
-
当a不为0时,进入while循环,
-
如果a不是空格时,那么就将a拷贝给b,
-
如果遇到空格的时候,就要在b后面加上%20 ,而b就向后面移动三个位置
(把空格替换成“%20”即相当于把一个字符替换成了三个字符,所以数组的长度的发生了变化) -
最后判断*b如果是‘\0’的时候就结束。
代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
int my_change(char *a, char *b)
{
while (*a)
{
if (*a != ' ')
{
*b = *a;
b++;
}
else
{
strcpy(b, "%20");
b = b + 3;
}
a++;
}
*b = '\0';
return 0;
}
int main()
{
char a[] = "abc defgx yz";
char b[40];
my_change(a, b);
printf("%s", b);
system("pause");
return 0;
}