把一个字符串如:we are happy中的空格替换为%20 输出 :we%20are%20happy
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
char* replaceSpace(const char* str)
{
int count = 0;
int len = 0;
char* oldstr = str;
char* newstr = NULL;
assert(str);
while (*oldstr++)
{
if (isspace(*oldstr))
count++;
}
len = strlen (str);
newstr = (char* )malloc((len+2*count)*sizeof(char));
if (NULL == newstr)
{
printf("out of merroy,return\n");
return ;
}
while (oldstr != str)
{
if (isspace(*oldstr))
{
*newstr-- = '0';
*newstr-- = '2';
*newstr-- = '%';
*oldstr -- ;
}
else
{
*newstr-- = *oldstr--;
}
}
*newstr = *oldstr;
return newstr;
}
int main()
{
char* _str ="we are happy";
printf("%s\n",replaceSpace(_str));
return 0;
}
\
先找出空格的数量,开辟能放下新字符串的空间,从后往前拷贝
这里返回的的newstr是新的字符串,但_str并没有改变,代码哪里需要改进,希望大家能够指教