4

JZ-002-替换空格

 2 years ago
source link: https://segmentfault.com/a/1190000040851436
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JZ-002-替换空格

发布于 10 月 22 日

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

题目链接: 替换空格

public class Jz02 {

    public static void main(String[] args) {
        StringBuffer strTest = new StringBuffer("We Are Happy");
        System.out.println(replaceSpace(strTest));

        StringBuffer strTest2 = new StringBuffer("We Are Happy");
        System.out.println(replaceSpace1(strTest2));
    }

    /**
     * 遍历每一个字符,替换空格
     *
     * @param str
     * @return
     */
    public static String replaceSpace(StringBuffer str) {
        StringBuffer str1 = new StringBuffer("");
        for (int i = 0; i < str.length(); i++) {
            if (' ' == str.charAt(i)) {
                str1.append("%20");
            } else {
                str1.append(str.charAt(i));
            }
        }
        return str1.toString();
    }

    /**
     * @param str
     * @return
     */
    public static String replaceSpace1(StringBuffer str) {
        int p1 = str.length() - 1;
        // 每一个空格再往后填充2个空格,当遇到空格时就有3个位置替换成 %20
        for (int i = 0; i <= p1; i++) {
            if (str.charAt(i) == ' ') {
                str.append("  ");
            }
        }
        int p2 = str.length() - 1;
        while (p1 >= 0 && p2 > p1) {
            char c = str.charAt(p1--);
            // 当遍历到第一个空格时,将连续的3个空格替换成 %20
            if (c == ' ') {
                str.setCharAt(p2--, '0');
                str.setCharAt(p2--, '2');
                str.setCharAt(p2--, '%');
            } else {
                str.setCharAt(p2--, c);
            }
        }
        return str.toString();
    }
}

【每日寄语】 脚步不停,初心不变。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK