题目描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
题目分析:
1.遍历字符串找到空格
2.用%20替换空格
3.返回新的字符串
对于这道题我的思路是利用两个指针从后向前遍历来进行替换
为什么是从后向前遍历而不是从前向后遍历呢?
从后向前处理,我们只需要在新的字符串末尾添加一个“\0”作为结束标识即可。
而新的字符串长度就应该是旧的字符串长度+空格个数*2
当str[index]遇到空格时,index向前移动一位,str[result]一次插入“%20”,然后将result向前移动三位
if (str[index] == ' ')
{
str[result] = '0';
str[result-1] = '2';
str[result-2] = '%';
index = index - 1;
result = result - 3;
}
不是空格的情况,index与result 同时向后走。
str[result--] = str[index--];
代码:
//请实现一个函数,将一个字符串中的每个空格替换成“%20”。
//例如,当字符串为We Are Happy.
//则经过替换之后的字符串为We%20Are%20Happy。
//
class Solution {
public:
void replaceSpace(char* str, int length)
{
//先计算源字符串内空格的个数
int OldLength = strlen(str);
if (OldLength <= 0)
{
return;
}
int BlockCount = 0;
for (int i = 0; i < OldLength; i++)
{
if (str[i] == ' ')
{
BlockCount++;
}
}
int NewLength = OldLength + BlockCount * 2;
int index = OldLength;
int result = NewLength;
str[NewLength] = '\0';
while (index >= 0 && result >= 0)
{
if (str[index] == ' ')
{
str[result] = '0';
str[result-1] = '2';
str[result-2] = '%';
index = index - 1;
result = result - 3;
}
else
{
str[result--] = str[index--];
}
}
cout << str << endl;
}
};
这里要注意的是while循环的退出条件是 index < 0 && result < 0
因此要考虑index与result等于0 也就是当前位置为字符串首的位置的情况。