In this loop, the program adds %20before each word:
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
This will lead to incorrect results, for example, for a bhe will give %20a%20b.
There is a much simpler solution:
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
Or, if you really do not want to use .replaceAll, write like this:
public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);
for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}
return sentence.toString();
}
janos source
share