Skip to content

Instantly share code, notes, and snippets.

@nashid
Last active October 31, 2016 20:20
Show Gist options
  • Save nashid/72a0fc34560b53d9d6559ba71500c9ca to your computer and use it in GitHub Desktop.
Save nashid/72a0fc34560b53d9d6559ba71500c9ca to your computer and use it in GitHub Desktop.
Replace blanks in a string with "%20"
package kata.string;
public class ReplaceBlank {
/**
* if you can use the String Buffer
*/
public String replaceBlankWithStringBuilder(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
sb.append("%20");
}
else {
sb.append(input.charAt(i));
}
}
return sb.toString();
}
public String replaceBlank(String inputStr) {
char[] output = null;
int numberOfBlanks = 0;
// find total number of blank space in the input string
for (int i = 0; i < inputStr.length(); i++) {
char ch = inputStr.charAt(i);
if (ch == ' ') {
numberOfBlanks++;
}
}
// create the output buffer
output = new char[inputStr.length() + 2 * numberOfBlanks];
// copy into the output array from the end
int inputEndPointer = inputStr.length()-1, outputEndPointer = output.length-1;
while (inputEndPointer >= 0) {
char ch = inputStr.charAt(inputEndPointer);
if (ch == ' ') {
output[outputEndPointer--] = '0';
output[outputEndPointer--] = '2';
output[outputEndPointer--] = '%';
}
else {
output[outputEndPointer--] = ch;
}
inputEndPointer--;
}
return new String(output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment