將字符串中的所有空格替換成%20

將字符串中的所有空格替換成%20

package array_2_3;

import java.util.Arrays;

/**
 * 將字符串"we are happy."替換成"we%20are%20happy."
 * 即把字符串的空格替換成%20
 */
public class Demo_5 {
    public static void main(String[] args) {
        String str = "we are happy.";
        Demo_5 demo = new Demo_5();
        int count = demo.theNumOfSpace(str);//字符串中空格的個數
        String[] res = demo.replace(str, count);
        System.out.println(Arrays.toString(res));
    }

    /**
     * 創建新長度字符串數組,用於copy
     * @param str
     * @param count:空格個數
     * @return
     */
    public String[] replace(String str, int count) {
        int finalLen = str.length() + 2*count;//count個空格,%20長度爲3,空格長度爲1,替換後新增長度=(3-1)*count
        String[] array = new String[finalLen];
        int p1 = str.length() - 1;//從字符串末尾開始作爲index
        int p2 = finalLen - 1;//從數組末尾開始作爲index
        while (p1 >= 0) {
            if (" ".equals(str.charAt(p1)+"")){
                array[p2--] = "0";
                array[p2--] = "2";
                array[p2--] = "%";
            }else {
                array[p2--] = str.charAt(p1)+"";
            }
            p1--;
        }
        return array;
    }

    /**
     * 字符串中空格個數
     * @param str
     * @return
     */
    public int theNumOfSpace(String str) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (" ".equals(str.charAt(i)+"")) {
                count++;
            }
        }
        return count;
    }
}

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