This is not very memory-efficient. Can you please suggest a better way or improvement?
public class Test{
public static void main(String[] args) {
System.out.println(replaceSpace("All men must die"));
}
public static String replaceSpace(String s) {
String[] stringArray = s.split(" ");
StringBuffer sb = new StringBuffer();
for(String s3 : stringArray) {
sb.append(s3);
sb.append("%20");
}
// if the last character is not space then, don't append %20.
if(s.charAt(s.length()-1) != ' ') {
return sb.substring(0, sb.length()-3).toString();
}
return sb.toString();
}
}
public class Test{
, I can tell because everywhere is properly aligned except here and after your code I see a trailing "}". In the future, you can highlight all of your code and push the button that looks like{ }
on the question editor and then it will put 4 spaces in front of each line so it properly formats all of your code in an easy manner. :) \$\endgroup\${}
button, and then pasted in their code. \$\endgroup\$