题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *string,int length) {
if(string == nullptr || length == 0)
{
return ;
}
int count_Blank = 0;
int count_str = 0;
int i = 0;
//找出空格数目
while(string[i] != '\0')
{
if(string[i] == ' ')
{
count_Blank++;
}
i++;
count_str++;
}
//数组最终的长度
int newlen = count_str + count_Blank * 2;
//数组元素溢出
if(newlen > length)
return ;
//开始存放
int indexOfNew = newlen, indexOfOriginal = count_str;
while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if(string[indexOfOriginal] == ' ')
{
string[indexOfNew--] = '0';
string[indexOfNew--] = '2';
string[indexOfNew--] = '%';
}
else
{
string[indexOfNew--] = string[indexOfOriginal];
}
--indexOfOriginal;
}
}
};