描述:请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
时间:2019-07-27 13:37
函数名:replaceBlack
思路:空格替换,掌握先开空间,再从后向前拷贝的思想,然后熟练运用指针来操纵数组的边界即可。此时的时间复杂度为O(n),但该题的前提是原数组要拥有足够多得空间来容纳替换后的字符串(包括’\0’)。
void replaceBlack(char string[], int length)
{
if (NULL == string || length <= 0)
{
return;
}
char *pcount = string;
int blackcount = 0;
int strlength = 0;
while (*pcount != '\0')
{
if (*pcount == ' ')
{
++blackcount;
}
++strlength; //比实际少一个字符串'\0'
++pcount;
}
char *fromend = pcount + 2 * blackcount;
while (strlength >= 0) //'\0'多拷贝一次
{
if (*pcount == ' ') //if后边不要写后置--,判断会执行这个操作
{
*fromend-- = '0';
*fromend-- = '2';
*fromend-- = '%';
pcount--;
}
else
{
*fromend-- = *pcount--;
}
strlength--;
}
}
int main()
{
char p[30] = {0}; //6
strcpy(p, "We are happy. "); //We%20are%20happy.%20'\0'
int length = sizeof(p)/sizeof(p[0]);
//cout << length<< endl;
show(p, length);
replaceBlack(p, length);
show(p, length);
return 0;
}
注意事项
- 在判断条件中尽量不要使用复合语句,这里主要指后置++或–
- ‘\0’的处理和我们源字符串指针最后的指向密切相关,正常情况下,无需做任何操作即可将’\0’拷贝
- 操纵指针的时候,时刻明白自己要干啥,把握好指针和数组的边界,防止越界程序崩溃或者打印奇异字符。