Web Toolbar by Wibiya

Pages

Sunday, April 17, 2011

Replace all spaces in a string with '%20'.

Solution #1: The most straight forward approach is to scan the entire string while copying it to another buffer and replacing each space with a '%20' in the new buffer. Time complexity will be O(n).

Solution #2: If we can assume that the string buffer is sufficiently large then we can scan the entire string to count the number of spaces and then modify the same string buffer by scanning it backwards and adjusting its length. Here is the code,

void replaceSpaces(char* str)
{
    int space_count=0;
    char* ptr = str;
    char* new_end = NULL;

    while(*ptr != '\0')
    {
        if(*ptr == ' ')
            space_count++;

        ptr++;
    }
        
    new_end = ptr + space_count*2;

    *new_end = '\0';
    
    while(ptr != str)
    {
        if(*ptr == ' ')
        {
            *new_end-- = '0';
            *new_end-- = '2';
            *new_end-- = '%';
        }
        else
        {
            *new_end-- = *ptr;
        }
        ptr--;
    }
}

No comments: