1. 程式人生 > >劍指offer-02:替換空格

劍指offer-02:替換空格

題目
請實現一個函式,將一個字串中的空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

public class Solution02 {

    public String replaceSpace(StringBuffer str) {
        if(str==null){
            return null;
        }
        StringBuilder newStr = new StringBuilder();
        for(int i=0;i<str.length
();i++){ if(str.charAt(i)==' '){ newStr.append('%'); newStr.append('2'); newStr.append('0'); }else{ newStr.append(str.charAt(i)); } } return newStr.toString(); } public static void
main(String[] args) { String a="We Are Happy."; System.out.print( new Solution02().replaceSpace(new StringBuffer(a))); } }