请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
void replaceSpace(char *str, int length) {
if (str == NULL || length < 1)
{
return;
}
int spaceCount = 0;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
{
++spaceCount;
}
}
int destLen = length + 2 * spaceCount;
int j = destLen - 1;
for (int i = length - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
str[j] = '0';
str[--j] = '2';
str[--j] = '%';
}
else
{
str[j] = str[i];
}
--j;
}
}
测试
void main() {
char str[] = "Hello world";
//char* str = "Hello world"; //不能这样用,char*指向的字符串不可修改
replaceSpace(str, strlen(str) + 1);
cout << str << endl;
getchar();
}
相关
1、C语言中"\0"和空格的区别
http://leoenglish.blog.163.com/blog/static/17503198520112945739709/
2,char *a 和 char a[]的区别
https://www.zhihu.com/question/26117197