Raw replacement of space by %20 in Java 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 &gt;= 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 &gt; spaceIdx; i--) {
        charr[i+2] = charr[i];
        charr[i] = ' ';
    }
    charr[spaceIdx] = '%';
    charr[spaceIdx+1] = '2';
    charr[spaceIdx+2] = '0';

  }
}
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&lt;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 &amp;&amp; foundIndex &lt;= maxIndex) {
        sb.append(input.substring(lastPoint, foundIndex - 1));
        sb.append(REPLACE_SPACE);

        lastPoint = foundIndex;
    }

    sb.append(input.substring(lastPoint));

    return sb.toString();
    }

}