给定一数组,将 空格 替换成 %20 ,要求时间复杂度为O(n)
void ReplaceBlank(char string[], int length)
{
if (string == NULL && length <= 0)
return;
int oldlength = 0;
int NumOfBlank = 0;
int i = 0;
while (string[i] != '\0')
{
++oldlength;
if (string[i] == ' ') //计算空格数
++NumOfBlank;
++i;
}
int newlength = oldlength + NumOfBlank * 2;//新数组长度
if (newlength > length)
return;
while (oldlength >= 0 && newlength > oldlength)//从后开始遍历
{
if (string[oldlength] == ' ')
{
string[--newlength] == '0';
string[--newlength] == '2';
string[--newlength] == '%';
--oldlength;
}
else
string[--newlength] = string[--oldlength];
}
}