(Replace spaces) Title Description :
Please implement a function, a string to replace each space to "20%." For example, when the string is We Are Happy. After the string is replaced after We% 20Are% 20Happy.
Solution one: use replace function
Replace method call after the string str into the spaces to "% 20" can be. Note that the result of the replace method call return value is the result of type String rather than void .
public class Solution { public String replaceSpace(StringBuffer str) { return str.toString().replace(" ", "%20"); } }
Solution two: use StringBuilder to append a new judge and results
char index = str.charAt (i); using this method to str through each character and with a new sbuilder receiving each character, the space in the back face append "% 20", and finally return sbuilder.toString () ;
public class Solution { public String replaceSpace(StringBuffer str) { StringBuilder sbuilder = new StringBuilder(); for(int i=0;i<str.length();i++){ char index = str.charAt(i); if(index == ' '){ sbuilder.append("%20"); }else{ sbuilder.append(index); } } return sbuilder.toString(); } }