请实现一个函数,将一个字符串中的字符串空格替换成“%20”.例如:“We Are Happy”转化后为“We%20Are%20Happy”
思路:把字符串转化成字符数组,判断这个字符是不是空格,如果是空格的话就拼接字符“%20”,否则就直接拼接字符数组中的值
package demo2; public class Main { public static void main(String[] args) { String str = "We Are Happy"; String result = replaceSpace(str); System.out.println(result); } public static String replaceSpace(String str){ StringBuffer sb = new StringBuffer(); char[] c = str.toCharArray(); for (int i=0;i<c.length;i++) { if (c[i] == ' ') { sb.append("%20"); } else { sb.append(c[i]); } } return sb.toString(); } }