I tried coding this for practice. Is there a more memory-efficient way to work in place without using more arrays etc (using raw array operations)?
public class SpaceUrlEncoder
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
String unencoded = "Mr John Smith ";
int lastCharIdx = 12;
char[] charr = unencoded.toCharArray();
for (int i = 12; i >= 0; i--) {
if (charr[i] == ' ') {
encodeSpaceAt(i, lastCharIdx, charr);
lastCharIdx += 2;
}
}
System.out.println("space encoded string: " + new String(charr));
}
public static void encodeSpaceAt(int spaceIdx, int lastCharIdx, char[] charr) {
for (int i = lastCharIdx; i > spaceIdx; i--) {
charr[i+2] = charr[i];
charr[i] = ' ';
}
charr[spaceIdx] = '%';
charr[spaceIdx+1] = '2';
charr[spaceIdx+2] = '0';
}
}
-
6\$\begingroup\$ Related questions: 1, 2, 3 \$\endgroup\$200_success– 200_success2017年03月17日 07:30:31 +00:00Commented Mar 17, 2017 at 7:30
1 Answer 1
We should understand what's happening when we do string-related operations in Java. When we concat strings in java, like
String result = "";
for(int i=0; i<100; i++){
result += i+","; // bad, because each string + string creates new string
}
Strings are immutable, so its bad to += them, instead, StringBuilder is used. Here's another way to solve this task:
public class ReplaceSpace {
private static final String REPLACE_SPACE = "%20";
private static final String SPACE = " ";
public static void main(String[] args) {
String input = "Just some input string to perform stuff !";
System.out.println(replaceString(input));
}
private static String replaceString(String input) {
StringBuilder sb = new StringBuilder();
int lastPoint = 0;
int foundIndex;
int maxIndex = input.length() - 1;
while ((foundIndex = input.indexOf(SPACE, lastPoint)) != -1 && foundIndex <= maxIndex) {
sb.append(input.substring(lastPoint, foundIndex - 1));
sb.append(REPLACE_SPACE);
lastPoint = foundIndex;
}
sb.append(input.substring(lastPoint));
return sb.toString();
}
}
Explore related questions
See similar questions with these tags.