《劍指offer》系列--替換空格

陽光總在風雨後,請相信一定有彩虹。

題目

請實現一個函數,把字符串中的每個空格替換成"%20",例如“We are happy.”,則輸出“We%20are%20happy.”。

解析

public class Test03 {
    public static String replaceSpace(String str){
        StringBuilder sb = new StringBuilder();
        for (int i = 0;i<str.length();i++){
            if (str.charAt(i) == ' '){
                sb.append("%20");
                continue;
            }
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String str = "we are happy.";
        System.out.println(replaceSpace(str));
    }
}

輸出結果:

we%20are%20happy.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章