将字符串“we are happy”转换为“we%20are%20happy”
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<ctype.h>
void My_Replace(char *arr)
{
char *start = arr;//"we are happy\0"start指向字符串首地址
char *end = NULL;
int old_len = 0;//计算代替前字符串的长度
int space_nums = 0;//空格的数目
assert(arr);//判断arr是否为空
while (*start != '\0')
{
if (isspace(*start))//如果start指向空格
{
space_nums++;
}
start++;//指向下一个元素
old_len++;
}
//start指向了字符串"we are happy\0"的\0
end = arr +old_len+ 2 * space_nums;//we%20are%20happy\0,end指向\0
while (start < end )
{
if (isspace(*start))//如果start指向空格时,用%20替换空格
{
*end-- = '0';
*end-- = '2';
*end = '%';
}
else
{
*end = *start;//如果start指向的不是空格,则将字符后移
}
start--,end--;
}
}
int main()
{
char str[60] = "we are happy";
My_Replace(str);
printf("%s\n",str);
system("pause");
return 0;
}