Monday, August 5, 2013

Coding Exercises Day 3 (Problem #5)

Problem:
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"

  void replaceSpaces(char[] charArray, int length) {
    int delta = 0;

    for (int i = 0; i < length; i++) {
      if (' ' == charArray[i + delta]) {
        for (j = delta + length - 1); j > i + delta; j--) {
          charArray[j + 2] = charArray[j];
        }

        charArray[i] = '%';
        charArray[i + 1] = '2';
        charArray[i + 2] = '0';      
        delta += 2;            
      }
    }
  }

No comments:

Post a Comment