字符串替换空格

时间:2022-11-05 14:58:15

字符串替换空格:
请实现一个函数,把字符数组中的每个空格替换成“%20”。
例如输入“we are happy.”,则输出“we%20are%20happy.”。

#include <stdio.h>
#include <assert.h>
#include <windows.h>
voidmy_replace(char *arr, int cap)
{
assert(arr);
assert(cap > 0);

intold_len = 0;
intspace_nums = 0;
char *start = arr;
while (*start != '\0'){//"we are happy.\0" ....[]
if (isspace(*start)){
space_nums++;
}
old_len++, start++;
}
intnew_len = old_len + space_nums*2+1;
//"a a"->a%20a\0
char* end = arr + new_len-1;
while (start >= arr){
if (isspace(*start)){
*end-- = '0';
*end-- = '2';
*end = '%';
}
else{
*end = *start;

}
start--, end--;
}
}

int main()
{
chararr[64] = "we are happy.";
my_replace(arr, sizeof(arr)/sizeof(arr[0]));
printf("%s\n", arr);
system("pause");
return 0;
}