ctci/01. Arrays and strings/1.3. replace_char.java

46 lines
1.2 KiB
Java

import CtCILibrary.AssortedMethods;
public class Question {
// Assume string has sufficient free space at the end
public static void replaceSpaces(char[] str, int trueLength) {
int numberOfSpaces = 0, index, i = 0;
for (i = 0; i < trueLength; i++) {
if (str[i] == ' ') {
numberOfSpaces++;
}
}
index = trueLength + numberOfSpaces * 2;
/* if there are excess spaces, add a null character, which indicates that the
* spaces after that point haven't been replaced with %20.
*/
if (trueLength < str.length) str[trueLength] = '\0';
for (i = trueLength - 1; i >= 0; i--) {
if (str[i] == ' ') {
str[index - 1] = '0';
str[index - 2] = '2';
str[index - 3] = '%';
index = index - 3;
} else {
str[index - 1] = str[i];
index--;
}
}
}
public static int findLastCharacter(char[] str) {
for (int i = str.length - 1; i >= 0; i--) {
if (str[i] != ' ') {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "Mr John Smith ";
char[] arr = str.toCharArray();
int trueLength = findLastCharacter(arr) + 1;
replaceSpaces(arr, trueLength);
System.out.println("\"" + AssortedMethods.charArrayToString(arr) + "\"");
}
}