package offer; public class Problem04 { /** * 把字符串中的每一個空格替換成「%20」。例如:輸入「We are happy」,則輸出「We%20are%20happy」。 */ public static void main(String[] args) { String str = "We are happy"; System.out.println(str.replace(" ", "%20")); } }
private static String replaceMethod(String s) { StringBuffer buffer=new StringBuffer(); if(s!=null){ for(int i=0;i<s.length();i++){ char ch=s.charAt(i); if(ch==' '){ buffer.append("%20"); }else{ buffer.append(ch); } } } return buffer.toString(); }