题目:一个字符串空间足够,把字符串中的每个空格替换成"%20",如"He ll o"替换为"He%20ll%20o"
思路:先遍历字符串,获得空格的个数,从而获取新字符串的长度。从字符串的尾部遍历字符串,逐个复制字符,遇到空格替换为%20.
#include <iostream>
void trimBlank(char arr[], int length)
{
if (arr == NULL || length <= 0) {
return;
}
int index = 0;
int blankNumber = 0;
while (arr[index]!= '\0') {
if (arr[index] == ' ') {
blankNumber++;
}
index++;
}
int replaceIndex = length + blankNumber * 2;
int i = length;
while (i >=0 && replaceIndex > i) {
if (arr[i] == ' ') {
arr[replaceIndex--] = '0';
arr[replaceIndex--] = '2';
arr[replaceIndex--] = '%';
} else {
arr[replaceIndex--] = arr[i];
}
i--;
}
}
int main(int argc, const char * argv[]) {
char a[20] = {'h', ' ', 'e','l','l', ' ', 'o'};
trimBlank(a, 7);
std::cout<<a<<std::endl;
return 0;
}