题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
#include <iostream>
using namespace std;
void replaceBlank(char str[], int length)
{
if(str == NULL || length <= 0)
return;
int originalLength = 0; /// 字符串初始长度
int numberOfBlank = 0; /// 空格的数量
int i = 0;
while(str[i] != '\0') /// '\0'是字符串的结束标志
{
++originalLength;
if(str[i] == ' ')
++numberOfBlank;
++i;
}
int newLength = originalLength + numberOfBlank * 2; /// 扩增后的长度
if(newLength > length) /// 在这里不扩充str[]的大小
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if(str[indexOfOriginal] == ' ') /// 如果某字符为空格
{
str[indexOfNew--] = '0';
str[indexOfNew--] = '2';
str[indexOfNew--] = '%';
}
else
{
str[indexOfNew--] = str[indexOfOriginal];
}
--indexOfOriginal;
}
}
int main()
{
char str[20] = "We are happy";
replaceBlank(str, 20);
cout << str << endl;
return 0;
}