题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入"We are happy."则输出"We%20are%20happy."。
分析:
方法一:创建新的字符串并分配足够多的内存,在新的字符串上进行替换。
方法二:从头到尾扫描字符串,每碰到一个空格的时候进行替换,并把空格后面的所有字符后移两个字节。
方法二的实现代码如下:
void Replace(char str[])
{
if (str == NULL)
{
return;
}
int i = 0;
while (str[i] != '\0')
{
int end = strlen(str);
if (str[i] == ' ')
{
while (end > i)
{
str[end + 2] = str[end];
end--;
}
str[i++] = '%';
str[i++] = '2';
str[i++] = '0';
}
i++;
}
}
方法三:先遍历一次字符串,统计出字符串中空格的总数,由此可以计算出替换之后的字符串的总长度(替换后的长度等于原来的长度加上2*空格数),然后从字符串的后面进行复制与替换。
方法三的实现代码如下:
void Replace(char str[])
{
if (str == NULL)
{
return;
}
int strlenth = 0;
int blanknum = 0;
int i = 0;
while (str[i] != '\0')
{
++strlenth;
if (str[i] == ' ')
{
++blanknum;
}
++i;
}
int newlength = strlenth + 2 * blanknum;
int indexstr = strlenth;
int indexnew = newlength;
while (indexstr >= 0 && indexnew > indexstr)
{
if (str[indexstr] == ' ')
{
str[indexnew--] = '0';
str[indexnew--] = '2';
str[indexnew--] = '%';
}
else
{
str[indexnew--] = str[indexstr];
}
--indexstr;
}
}