Write a method to replace all spaces in a string with ‘%20’.
char * replace(char * chr)
{
char * start = chr;
int length = 0;
int n_space = 0;
while (*start != '\0')
{
length ++;
start ++;
if (*start == ' ')
n_space ++;
}
start = chr;
char * newchr = new char[length + 2 * n_space + 1];
newchr[length + 2 * n_space] = '\0';
start = chr;
while (*start != '\0')
{
if (*start == ' ')
{
*newchr++ = '%';
*newchr++ = '2';
*newchr++ = '0';
}
else
{
*newchr++ = *start;
}
start ++;
}
return newchr;
}