URLify

1.3 URLify: 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.)

#include <iostream>
#include <string>

using namespace std;

// Run-Time Check Failure #2 - S
// http://stackoverflow.com/questions/37128968/run-time-check-failure-2-s-visual-studio-c/37129017#37129017
// O(n) algorithm
// O(1) space
void replaceSpace(char *s, int length) {
    int spaces = 0;
    for (int i = 0; i < length; i++) {
        if (s[i] == ' ') {
            spaces++;
        }
    }

    // new string that includes overwriting space, and two additional chars
    int newLen = length + spaces * 2;

    s[newLen] = '\0';
    for (int i = length - 1; i >= 0; i--) {
        if (s[i] == ' ') {
            s[newLen - 1] = '0';
            s[newLen - 2] = '2';
            s[newLen - 3] = '%';
            newLen -= 3;
        }
        else {
            // working backwards, replace everything
            s[newLen - 1] = s[i];
            --newLen;
        }
    }
}

int main()
{
    char test[] = "rep lace Spac e\0";
    replaceSpace(test, 16);
    cout << test << endl;

}

Last updated