#include #include #include #include /* Sample midterm question: Write a function to replace all spaces in a string with ‘%20’. */ int main(int argc, char ** argv) { if (argc != 2) { fprintf(stderr, "Usage: encode string\n"); exit(1); } char * str = argv[1]; int len = strlen(str); int count = 0; for (int i = 0; i < len; i++) { if (str[i] == ' ') { count++; } } count *= 2; int newlen = len + count; char * newstr = (char *)malloc((newlen+1) * sizeof(str[0])); newstr[newlen] = '\0'; for (int i = len-1; i >= 0; i--) { if (str[i] == ' ') { newstr[newlen - 1] = '0'; newstr[newlen - 2] = '2'; newstr[newlen - 3] = '%'; newlen -= 3; } else { newstr[newlen - 1] = str[i]; newlen -= 1; } } printf("Old: %s. New: %s\n", str, newstr); free(newstr); return 0; }