Question

URLify

Replace all spaces with %20.


 int getNumSpaces(char* string, int length) {
    int n = 0;
    for (int i = 0; i < length; i++) {
        if (string[i] == ' ') {
            n++;
        }
    }
    return n;
}

void URLify(char* string, int actual_length) {
    const int num_spaces = getNumSpaces(string, actual_length);
    const int additional_spaces = num_spaces * 2;
    int readidx = actual_length - 1; // backward
    int writeidx = readidx + additional_spaces;
    while (readidx >= 0)
    {
        assert(writeidx >= readidx);
        if (string[readidx] != ' ') {
            string[writeidx--] = string[readidx];
        }
        else if (string[readidx] == ' ') {
            string[writeidx--] = '0';
            string[writeidx--] = '2';
            string[writeidx--] = '%';
        }

        readidx--;
    }
}


 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s