我没有看到错误。(Mailto的转换代码)



我的意图是将字符串转换为mailto,但我发现了一个问题,当我设置特征线时,删除所有并只设置最后一行。

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
}

不要手动滚动URL编码(很容易出错!(,请使用现有的URLEncoder

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

注意,这会产生一个略有不同(但有效(的结果:空间被编码为+,而不是%20

如果出于某种原因,您想要/需要编写自己的特别电子邮件编码器,您可以使用String.replace:缩短代码

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

如果您关心性能(要小心实际测量!(,不要通过串联来构造字符串,而是使用StringBuilder

再加上对代码的修复,以及为提高可读性而进行的轻微重写,这就产生了

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();
}
public String mailto(String texto){
String total="";
for (int i = 0; i < texto.length(); i++)
if(texto.charAt(i)==' ') {
total = total + "%20";
} else if(texto.charAt(i)=='n'){
total = total + "%0D%0A";
} else {
total += texto.charAt(i);
}
}
return total
}

为了减少测试次数,可以颠倒逻辑:首先检查' ''n'

最新更新