Skip to content

Instantly share code, notes, and snippets.

@EnesKorukcu
Last active August 29, 2015 14:16
Show Gist options
  • Save EnesKorukcu/ffe60030d98122b8d1e3 to your computer and use it in GitHub Desktop.
Save EnesKorukcu/ffe60030d98122b8d1e3 to your computer and use it in GitHub Desktop.
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 static String replaceSpaces(String input) {
char[] inputChars = input.toCharArray();
StringBuilder stringBuilder = new StringBuilder(input);
for(int i = 0; i < inputChars.length; i++) {
if(inputChars[i] == ' ') {
stringBuilder.append("%20");
} else {
stringBuilder.append(inputChars[i]);
}
stringBuilder.deleteCharAt(stringBuilder.length() - i);
}
return stringBuilder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment