Problem
Replace spaces in sentences with "%20"
Solution
#include <iostream>
#include <string>
using namespace std;
void replace_space(char* str)
{
char *space = "%20";
int len = strlen(str);
if(len ==0){
return;
}
int i;
int space_num = 0;
for(i = 0; i < strlen(str); i++){
if(str[i] == ' ' || str[i] == '\t'){
space_num ++;
}
}
if(space_num == 0)
return;
int len_after;
len_after = len + space_num * 2;
str[len_after] = '\0';
for(i = len-1; i >= 0; i--){
if(str[i] == ' ' || str[i] == '\t'){
str[len_after--] = '0';
str[len_after--] = '2';
str[len_after--] = '%';
}
else{
str[len_after--] = str[i];
}
}
}
int main(int argc, char* argv[])
{
char str[100] = " aa bb cc\t !";
cout << "before replace :" << str << endl;
replace_space(str);
cout << "after replace :" << str << endl;
return 0;
}
output
before replace : aa bb cc !
after replace : %20aa%20bb%20cc%20%20!