Replace ' ' Spaces in a URL with a '%20' - Coding Challenge This was a small coding challenge proposed at my school. The problem is:


  Given a string (or URL), replace the white-spaces inside of the string
  with %20, but any spaces on the outside should not be included.
  
  For example, input " Mr John Smith " would return "Mr%20John%20Smith".


I have completed this challenge successfully using the code below. My question is, is there any way to improve the efficiency? I believe the complexity is currently \$O(2n) = O(n)\$ given the 2 for loops. I do not want to use any libraries or functions like str.replace(). But I'm assuming there is a better way than trimming and then counting the whitespace.

public class URL {

    /**
     * @description URLify ~ A small method that makes a string with spaces URL Friendly!
     * @param str
     * @param length
     * @return String
     */

    public static String URLify(String str) {
        str = str.trim();
        int length = str.length();
        int trueL = length;
        if(str.contains(" ")) {
            for(int i = 0; i &lt; length; i++) {
                if(str.charAt(i) == ' ') {
                    trueL = trueL + 2;
                }
            }
            char[] oldArr = str.toCharArray();
            char[] newArr = new char[trueL];
            int x = 0;
            for(int i = 0; i &lt; length; i++) {
                if(oldArr[i] == ' ') {
                    newArr[x] = '%';
                    newArr[x+1] = '2';
                    newArr[x+2] = '0';
                    x += 3;
                } else {
                    newArr[x] = oldArr[i];
                    x++;
                }
            }
            str = new String(newArr, 0, trueL);
        }
        return str;
    }
    public static void main(String[] args) {
        String str = "     https://google.com/  testing  .pdf    ";
        str = URLify(str);
        System.out.print(str);
    }
}


Note: I am looking for any criticism. I would really like to improve my skills in general.
From a short review:


If you are going to write your own replace, then you should create a method for it, so that you can call myReplace( string, target, replacement);
Personally I would have checked if args got a String, and only if nothing is provided would I use the hard coded string, that would make it easier to show and test your design
No reason to do this in 2 lines:

str = URLify(str);
System.out.print(str);


you can just write

System.out.print(URLify(str));

Javadoc commenting looks good (but is not actually true?), otherwise there are zero comments
I am pretty you can merge those 2 loops into one if you used a stringbuilder. On the whole the replace algorithm could use work