1
\$\begingroup\$

I have written a code to replace all spaces in a String with %20.

Input: "Mr John Smith "
Output: "Mr%20John%20Smith"

My logic:

public class URLify {
    public static void main(String[] args) {
        String str = "Mr John Smith  ";
        str = str.stripTrailing();
        char[] ch = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(char c : ch) {
            if(c != ' ')
                sb.append(c);
            else {
                sb.append("%20");
            }
        }
        System.out.println(sb.toString());
    }
}

The given solution:

static int MAX = 1000; 
static char[] replaceSpaces(char str[]) {
    int space_count = 0, i = 0;
    for (i = 0; i < str.length; i++)
        if (str[i] == ' ')
            space_count++;
    while (str[i - 1] == ' ') {
        space_count--;
        i--;
    }
    int new_length = i + space_count * 2;
    if (new_length > MAX)
        return str;
    int index = new_length - 1;
    char[] old_str = str;
    str = new char[new_length];
    for (int j = i - 1; j >= 0; j--) {
        if (old_str[j] == ' ') {
            str[index] = '0';
            str[index - 1] = '2';
            str[index - 2] = '%';
            index = index - 3;
        }
        else {
            str[index] = old_str[j];
            index--;
        }
    }
    return str;
}

Both work correctly with a linear time complexity of 𝑂(𝑛) however, can someone please suggest which solution is a better one especially if asked in an interview? Thanks!

\$\endgroup\$
2
  • \$\begingroup\$ What was the language for the given solution? \$\endgroup\$ – pacmaninbw Apr 17 at 17:57
  • \$\begingroup\$ The language was java \$\endgroup\$ – salazarin Apr 17 at 18:09
2
\$\begingroup\$

Your code does what you describe, but the code does not what it is really supposed to do.

You are not the first person ever who needs to convert an arbitrary string into a form that can be embedded in a URL. Several people before you have already solved this problem. The crucial point is to know how these people named the method or function or class or module where they implemented this function.

In Java, most network-related things are in the package java.net, and since URLs and URIs are network-related, they are there as well. Directly next to the classes URL and URI you will find the class URLEncoder that does all the work for you, including several edge cases you probably never heard of. Using this heavily tested and well-known piece of code is much better than rolling your own.

Hmmm, a pretty heavy down-side of Java's URLEncoder is that it is old and dusty and probably will not be updated anymore. It does not even encode spaces as %20, but as +, and the + is something that only works in the query string part of a URL.

This Stack Overflow answer describes the bad API that standard Java is providing for this use case. The encoding part of this answer to that question is good, the general Java approach is bad, as I wrote in the comment below that answer. So be careful and don't copy that code blindly.

\$\endgroup\$
2
\$\begingroup\$

Review

Welcome to Code Review. There are some suggestions as follows.

Consider to use replaceAll

The operation you performed is what String.replaceAll do, you can use replaceAll directly instead of String.toCharArray(), whitespace comparison, and sb.append things.

Create a method URLify

In order to improve usability, it is better to create a method URLify to perform this specific operation.

Summary

Combine all the things:

public class URLify {
    
    public static String URLify(String input){
        return input.stripTrailing().replaceAll(" ","%20");
    }
    
    public static void main(String[] args) {
        String str = "Mr John Smith  ";
        System.out.println(URLify(str));
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ No need to use replaceAll, a simple replace is sufficient. (Yes, I know that the method names are confusing, but they cannot be improved anymore since too much existing code relies on them.) \$\endgroup\$ – Roland Illig Apr 18 at 23:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.