CTCI: Ch. 1-4

Write a method to replace all spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the “true” length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)
EXAMPLE
Input: “Mr John Smith ”
Output: “Mr%20John%20Smith”

#include <iostream>
#include <cstring> // for strlen, but in Xcode, it's not necessary to include this
using namespace std;

void replaceSpaces(char originalStr[])
{
    int spaceCount = 0;
    int newLength = 0;
    int length = (int)strlen(originalStr);
    for(int i=0;i<length;i++)
    {
        if(originalStr[i] == ' ')
            spaceCount++;
    }
    newLength = length + spaceCount * 2; //not * 3 because original space has been counted once
    originalStr[newLength] = '\0'; //string terminate
    for(int i = length -1;i>=0;i--)
    {
        if(originalStr[i] == ' ')
        {
            originalStr[newLength - 1] = '0';
            originalStr[newLength - 2] = '2';
            originalStr[newLength - 3] = '%';
            newLength-=3;
        }
        else
        {
            originalStr[newLength - 1] = originalStr[i];
            newLength--;
        }
    }
}

int main(int argc, const char * argv[])
{
    char ch[] = "Mr John Smith";
    replaceSpaces(ch);
    cout<<ch<<endl;
    return 0;
}

 

3 thoughts on “CTCI: Ch. 1-4

  1. char operation:

    char *ch = const char *ch

    So, the value of ch cannot be modified!

    If you would like to modify the value of ch, then 

    char ch[] = "abcde\0";
    ch[0] = 'x';

    Consider the length of a char array,

    strlen(ch) doesn't count the null character (\0)

    Thus, 

    char ch[] = "abcde\0" // strlen(ch) = 5, not 6
    //if you want to use a static char array, you need to alloc an array of size 6
    char ch[6] = {'a', 'b', 'c', 'd', 'e', '\0'}; // strlen(ch) = 5

     

  2. void charRef(char *ch)
    {
        ch[0] = 'X';
    }
    int main()
    {
        char str[] = "abcde";//if char *str="abcde\0", ch[] cannot be modified
        cout<<str<<endl;//abcde
        charRef(str);
        cout<<str<<endl;//Xbcde
        return 0;
    }

Leave a Reply