Replace space with %20

Given any string, replace spaces with "%20"
/*
 * ReplaceSpace.cpp
 *
 *  Created on: Apr 10, 2012
 *      Author: Kiran Hegde
 */

#include <string.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int countSpaces(char *str) {
    int count = 0;
    if (str != NULL) {
        while (*str++ != '\0') {
            if (*str == ' ')
                count++;
        }
    }
    return count;
}

void replaceSpaces(char *&str) {
    int oldLength = strlen(str);
    int noOfSpaces = countSpaces(str);
    int newLength = oldLength + (2*noOfSpaces);

    int newIndex = newLength;
    str[newIndex] = '\0';
    for (int i=oldLength-1; i>=0; i--) {
        if (str[i] == ' ') {
            str[newIndex - 1] = '0';
            str[newIndex - 2] = '2';
            str[newIndex -3] = '%';
            newIndex = newIndex - 3;
        }
        else {
            str[newIndex-1] = str[i];
            newIndex--;
        }
    }
}

/**
 * Test the function
 */
int main() {
    char *test = (char *)malloc(sizeof(char)*256); // create string with enough space at the end
    strcpy(test, "replace space with 3 chars");
    cout << test << endl;
    replaceSpaces(test);
    cout << test << endl;
}
Comments