Search code examples
javastringmailtofor-in-loop

I don't see the mistake. (Conversion code for Mailto)


My intentions is convert a String for mailto but, I found a problem, when I set breakline remove all and set only the last line.

public String mailto(String texto){
    String total="";

    for (int i = 0; i < texto.length(); i++)
        if (texto.charAt(i)!=' ' && texto.charAt(i)!='\n'{
            total += texto.charAt(i);
        } else {
            if(texto.charAt(i)==' ') {
                total = total + "%20";
            } else {
                if(texto.charAt(i)=='\n'){
                    total = total + "%0D%0A";
                }
            }
        }
    }
    return total
}

Solution

  • Don’t hand-roll URL encoding (it’s quite easy to get wrong!), use the existing URLEncoder for that.

    public String mailto(String texto) {
        return URLEncoder.encode(texto);
    }
    

    Note that this yields a slightly different (but valid) result: space is encoded as + instead of as %20.

    If for some reason you want/need to write your own ad-hoc email encoder, you can shorten your code by using String.replace:

    public String mailto(String texto) {
        return texto.replace(" ", "%20").replace("\n", "%0D%0A");
    }
    

    If you’re concerned about performance (be careful to actually measure!), don’t construct your string via concatenation, use a StringBuilder instead.

    Together with the fixes of your code, as well as a slight rewrite to increase readability, this yields

    public String mailto(final String texto) {
        final StringBuillder sb = new StringBuilder();
    
        for (int i = 0; i < texto.length(); i++) {
            final char c = texto.charAt(i);
            if (c == ' ') {
                sb.append("%20");
            } else if (c == '\n') {
                sb.append("%0A%0D");
            } else {
                sb.append(c);
            }
        }
    
        return sb.toString();
    }