1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // Author: Sheng Yu // Date: 02/09/2013 // // C solution for problem 1.4 in Cracking the Coding Interview 5th eidtion. // // Test environment: gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52) // #include <stdio.h> #include <string.h> void ReplaceSpaces(char *str, int len){ /* To replace all the spaces in str to "%20" in in-place manner*/ int index = -1; int old_end = len-1; int new_end = old_end; // Compute the end of new string while(++index<len){ if(str[index]==' '){ new_end += 2; } } // Replace the " " to "%20" str[new_end+1] = ' '; while(--index >=0){ if(str[old_end]==' '){ str[new_end--] = '0'; str[new_end--] = '2'; str[new_end--] = '%'; } else{ str[new_end--] = str[old_end]; } --old_end; } return; } int main(){ char test[50] = "Mr John Smith "; printf("Original: %sn",test); ReplaceSpaces(test,strlen(test)); printf("Replaced: %sn",test); return 0; } |
Unofficial C Solution to Problem 1.4 in Cracking the Coding Interview (5th Edition)
9 Feb