您的位置:首页 > Web前端

剑指offer之替换字符串中的空格

2016-04-10 11:47 309 查看
题目:请实现一个函数,把字符串中的每个空格替换成“%20”。

例子:”we are” ====>”we%20are”。

思路:一看到这题直接能想到的方法就是===>从头开始遍历字符串

每遇到空格,换成%20,直到遍历完字符串。但是如果之前的字符串空间有限,则这样做会产生内存覆盖。

法二:前提===>源字符串空间充足。可以一次遍历出字符串有多少个空格,然后计算出新字符串的长度,然后进行替换。

代码如下:

void ReplaceBlank(char str[], int length)
{
assert(str != NULL &&length > 0);
int i = 0;
int Oldlength = 0;
int blankcount = 0;
while (str[i] != '\0')
{
++Oldlength;
if (str[i] == ' ')
{
++blankcount;
}
++i;
}
int Newlength = Oldlength + blankcount * 2;
if (Newlength > length)
return;
int indexOld = Oldlength;
int indexNew = Newlength;

while (indexOld >= 0 && indexNew > indexOld)
{
if (str[indexOld] == ' ')
{
str[indexNew--] = '0';
str[indexNew--] = '2';
str[indexNew--] = '%';
}
else
{
str[indexNew--] = str[indexOld--];
}
}
}
int main()
{
const int length = 100;
char str[length] = "hello world";
ReplaceBlank(str, length);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: