I have implemented a solution to this Cracking the Coding Interview question:
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. USE character array to perform this operation in place.
public static String conversion(String str, int length){
char[] strChars = str.toCharArray();
int numSpaces = 0;
for(int i = 0; i < length; i++){
if(strChars[i] == ' ')
numSpaces++;
}
int newLength = length + 2 * numSpaces;
char[] newChars = new char[newLength];
for(int i = length - 1; i >= 0; i--){
char c = strChars[i];
if(c != ' '){
newChars[i + 2 * numSpaces] = c;
}
else{
newChars[i + 2 * numSpaces] = '0';
newChars[i + 2 * numSpaces - 1] = '2';
newChars[i + 2 * numSpaces - 2] = '%';
numSpaces--;
}
}
String newString = String.valueOf(newChars);
return newString;
}
Can anyone give me any feedback on my implementation in regards of efficiency or improvements?