例如输入“we are happy”,则输出“we%20are%20happy”
想要实现这个目的,先观察下面的函数实现原理图。
先通过遍历字符数组,找出其中的空格数,计算出应该移动到的位置,接着就是移动指针,并在遇到空格时插入%20,函数便可实现。
具体实现代码如下:
#include <stdio.h>
char replace(char* src)
{
int count = 0;
char *end = NULL;
char *pend = NULL;
char *str = src;
while (*str)
{
if (*str == ' ')
{
count++;
}
str++;
}
end = str - 1;
pend = end + 2 * count;
while (end != pend)
{
if (*end != ' ')
{
*pend-- = *end--;
}
else
{
*pend-- = '0';
*pend-- = '2';
*pend-- = '%';
end--;
}
}
printf("%s\n", src);
}
int main()
{
char src[30] = "we are happy.";
replace(src);
system("pause");
return 0;
}