剑指offer Java实现 第五题

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

实现代码:

public static String replaceSpace(StringBuffer str) {
    if (str == null||str.length() == 0){
        return null;
    }
    int spaceNum = 0;
    for (int i=0;i < str.length();i++){
        if (str.charAt(i) == ' '){
            spaceNum++;
        }
    }
    StringBuffer result = new StringBuffer(20);
    int p1 = str.length() - 1;
    int p2 = str.length() + spaceNum*2 - 1;
    while (p1 != -1){
        if (str.charAt(p1) != ' ') {
            result.append(str.charAt(p1));
            p1--;
            p2--;
        }else {
            result.append('0');
            p2--;
            p1--;
            result.append('2');
            p2--;
            result.append('%');
            p2--;
        }
    }
    result = result.reverse();
    return result.toString();
}

    public static void main(String[] args){
        StringBuffer sb = new StringBuffer("We are happy.");
        System.out.println(replaceSpace(sb));
    }

你可能感兴趣的:(剑指offer)