Cracking The Coding Interview/Q 1.4

From Software Engineers Wiki
Jump to: navigation, search

Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)


  • Input: "Mr John Smith
  • Output: "Mr%20Dohn%20Smith"


First count number of spaces. If there is no space, there is nothing to do. Based on the number of strings, you can find what will be the new length. You can start working from new end of the string, and do it in place.

char *replaceSpace(char *str)
        char *cpDst, *cpSrc;
        int countSpace;
        int len;

        /* count number of spaces, number of character */
        for (cpSrc = str, countSpace = 0, len = 0; *cpSrc != '\0'; ++cpSrc) {
                if (*cpSrc == ' ')

        if (countSpace == 0)
                return 0;

        /* cpSrc is at null character. 
         * cpDst will point to the location of new null character
         * At first iteration, the null character will be copied.
        for (cpDst = str + len + countSpace * 2; cpSrc >= str; --cpSrc) {
                if (*cpSrc == ' ') {
                        *cpDst-- = '0';
                        *cpDst-- = '2';
                        *cpDst-- = '%';
                        if (--countSpace == 0)
                } else
                        *cpDst-- = *cpSrc;

        return str;

And a simple test program.

int main(void)
        char str[256] = " hello, world! ";

        std::cout << replaceSpace(str) << "\n";

        return 0;

And the result is as expected.

Personal tools