Attention:
The content in the article comes from book "Code interview".
Question:
Please implement a function to replace each blank in a string with “%20”. For instance, it outputs “We%20are%20happy.” if the input is “We are happy.”.
Answer:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void replace_str( char * str, int buff_size, int str_len )
{
int i = buff_size - 2;
int j = str_len - 1;
while ( j ) {
if ( str[j] == ' ' ) {
str[i] = '0';
str[i - 1] = '2';
str[i - 2] = '%';
--j;
i-=3;
} else {
str[i] = str[j];
--j;
--i;
}
}
}
int main(int argc, char* argv[])
{
char str[18] = { 0 };
strcpy( str, "We are happy." );
printf( "%s\n", str );
replace_str( str, sizeof(str), strlen(str) );
printf( "%s\n", str );
getchar();
}
评论