替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
方法1:replace函数
public String replaceBackend(String word){ String a = word.toString(); String b = a.replaceAll(" ","%20"); return b; }
方法2:转换成数组再去拼吧吧吧吧
public String replaceBackend(String word){ String a = word.toString(); char[] b = a.toCharArray(); StringBuffer c = new StringBuffer(); for(int i = 0 ;i<b.length;i++){ if(b[i] == ' '){ c.append("%20"); }else{ c.append(b[i]); } } return c.toString(); } public static void main(String args[]){ String word = "we are happy"; aaa a = new aaa(); System.out.println(a.replaceBackend(word)); }