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.)

EXAMPLE

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

Answer

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) {
                ++len;
                if (*cpSrc == ' ')
                        ++countSpace;
        }

        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)
                                break;
                } 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.

%20hello,%20world!%20
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox