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 to hold the additional characters, and that you are given the "true" length of the string. EXAMPLE Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith"

Algorithm:

#include <stdio.h>


char* URLify(char* testStr, int len){
    
    int countSpace = 0;
    
    int i = 0;
    while(testStr[i] != '\0'){
        if( testStr[i] == ' '){
            countSpace++;
        }
        i++;
    }
    
    int realLen = len + countSpace * 2;
    testStr[realLen] = '\0';
    
    for(int i = len - 1; i >= 0; i--){
        if(testStr[i] == ' '){
            testStr[realLen - 1] = '0';
            testStr[realLen - 2] = '2';
            testStr[realLen - 3] = '%';
            realLen -= 3;
        }else{
            testStr[realLen - 1] = testStr[i];
            realLen--;
        }
    }
    return testStr;
}

Test:

int main(){

    //*** stack smashing detected ***: terminated
    //char testStr1[6] = "ab cd";
    char testStr1[100] = "ab cd";
    printf("URLify = %s\n", URLify(testStr1, 6));

    return 0;
}

Last updated