将字符串中的所有空格替换成%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;
    }
}

猜你喜欢

转载自blog.csdn.net/tmax52HZ/article/details/106597860
今日推荐