08:字符串替換空格

題目:替換空格

實現一個函數,存在字符串hello world!!!,將字符串內的空格字符替換爲’%20’。
先對空格個數進行計數,得到適當大小的字符數組,接着將原本數組從後向前替換到新數組中。

public class Offer08 {
    public static void main(String[] args) {
        String string = "hello world! !";
        System.out.println(replaceBlank(string));
    }
    public static String replaceBlank(String str){
    	if(str==null||str.length()==0)return null;
        char[] chars = str.toCharArray();
        //空格計數
        int count=0;
        for (char c : chars) {
            if(c==' ')count++;
        }
        //新數組大小
        int ti = count*2+chars.length;
        char[] temp = new char[ti];
        //下標
        ti--;
        //替換
        for (int i=chars.length-1;i>=0;i--){
            if(chars[i]==' '){
                temp[ti--] = '0';
                temp[ti--] = '2';
                temp[ti--] = '%';
            }else{
                temp[ti--] = chars[i];
            }
        }

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