Saturday, October 3, 2015

[1.5] Replce all space in a string with '%20'

1. Example

s              = "I am so."
replacedS= "I%20am%20so."

2. Implementation


// Assume the length of char[] is enough to hold 
// all replaced string  
public static void replaceSpace(char[] str, int length)
{



    int spaceCount = 0; newLength, i = 0;
    for (i = 0; i < length; i++)
    {
        if (str[i] == ' ')
           spaceCount++;
    }



    
    // I am so
    // o
    //             o\0
    // s          
    //
    //            so\0  
    // ' '
    //         %20so\0 
    newLength = length + spaceCount*2;
    str[newLength] = '\0';
    for ( int i= length-1; i >= 0; i-- )
    {
         if (  str[i] == ' ' )
         {
             str[newLength -1] = '0';
             str[newLength -2] = '2';
             str[newLength -3] = '%';
             newLength = newLength -3;
         }
         else 
         {
             str[newLength-1] = str[i];
             newLength = newLength -1;
         }
    }



}
3. Similar Ones


No comments:

Post a Comment