4
\$\begingroup\$

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';
 }
}
asked Mar 17, 2017 at 7:18
\$\endgroup\$
1
  • 6
    \$\begingroup\$ Related questions: 1, 2, 3 \$\endgroup\$ Commented Mar 17, 2017 at 7:30

1 Answer 1

1
\$\begingroup\$

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();
 }
}
answered Feb 5, 2018 at 18:58
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.