双指针方法
替换空格
http://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
class Solution {
public:
void replaceSpace(char str,int length) {
if (str == nullptr || length <= 0)
return;
/*originalLength 为字符串string的实际长度/
char str0 = str; //保留初始数组指针位置
int originalLength = 0;
int numberOfBlank = 0;
while(str != '\0')
{
++ originalLength;
if (str == ' ')
++ numberOfBlank;
++ str;
}
if (originalLength + 2numberOfBlank >length)
return;
char *newstr = str; // 设置第二个指针
while (numberOfBlank > 0)
{
++ newstr;
++ newstr;
-- numberOfBlank;
}
/双指针从后向前运行/
while (str != str0)
{
if (str == ' ')
{
*newstr-- = '0';
*newstr-- = '2';
*newstr-- = '%';
}
else
{
*newstr-- = *str;
}
--str;
}
if (str == ' ')
{
*newstr-- = '0';
*newstr-- = '2';
*newstr-- = '%';
}
else
{
*newstr-- = *str;
}
}
};