Wednesday, June 19, 2013

cc150_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.)

public void replaceSpaces(char[] str, int length) {
  int spacecount = 0, newlength, index;
  for(int i = 0; i < length; i++){
     if(str[i] == ' ') spacecount++;
  }
  index = length + (spacecount<<1);
  str[index--] = '\0';
  for(int i = length - 1; i >= 0; i--){
       if(str[i] != ' ') str[index--] = str[i];
       else{
          str[index--] = '0';
          str[index--] = '2';
          str[index--] = '%';
      }
  }
}


No comments:

Post a Comment