we are happy 把空格换成 %20 剑指offer P44

public class StringReplace {
    public static void replaceSpace(String[] str, int length) {
        if(str == null || length <= 0) {
            return;
        }
        int originalLength = 0;
        int numberOfBlank = 0;
        int i = 0;
        while(str[i] != null) {
            originalLength ++;
            if(str[i] == " ") {
                numberOfBlank ++;
            }
            i++;
        }
        //新的字符串长度
        int newLength = originalLength + 2 * numberOfBlank;
        if(newLength > length) {//不能超出字符数组的长度
            return;
        }
        int originalIndex = originalLength-1;
        int newIndex = newLength-1;
        while(originalIndex >=0 && originalIndex < newIndex) {
            if(str[originalIndex] == " ") {
                str[newIndex--] = "0";
                str[newIndex--] = "2";
                str[newIndex--] = "%";
                originalIndex --;
            }else {
                str[newIndex--] = str[originalIndex--];
            }
            
        }
        
    }
    
    public static void main(String[] args) {
        String[] temp = {"we", " ","are", " ", "happy",null,null,null,null,null,null,null,null };
        replaceSpace(temp,13);
        for(int i=0; i< temp.length; i ++) {
            System.out.print(temp[i]);
        }
    }

}

 

posted @ 2016-02-29 19:07  笨狗毒毒毒  阅读(252)  评论(0编辑  收藏  举报