题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入"We are happy.",则输出"We%20are%20happy."。
看了原文的代码觉得。。有点麻烦。。
自己搞了老半天
大佬请不要吐槽。。
char *replace_space(char s[])
{
int len = strlen(s) + 1;
if(len == 0)
return 0;
int numspace = 0;
for(int i = 0; i < len; i++)
{
if(s[i] == ' '){
numspace++;
}
}
char *new_s = new char[(len + 3) * sizeof(char)];
strcpy(new_s, s);
for(int i = 0; i < len + 3*numspace; i++)
{
if(new_s[i] == ' '){
for(int j = strlen(new_s) - 1; j > i; j-- ){
*(new_s + j + 2) = *(new_s + j);
}
*(new_s + i) = '-';
*(new_s + i + 1) = '-';
*(new_s + i + 2) = '-';
}
}
return new_s;
}
int main()
{
char str[16] = "we are happy1.";
cout<<("%s", replace_space(str)) << endl;
return 0;
}