劍指offer-2替換空格爲指定字符串

 該題是劍指offer的基礎題,輸入一個字符串,裏面有一些空格,將空格填寫“%20”這三個字符。然後輸出。

下面是簡單代碼。

public class Test0401{
    public static void  replaceblank(char[] string,int usedLength) {
        //統計空白字符數
        int blanknum = 0;
        for (int i = 0; i < 5; i++) {
            if (string[i] == ' ') { //空字符要用單引號
                blanknum++;
            }
        }
        int TargetLength = usedLength + blanknum*2;
        while (usedLength > 0 && usedLength< TargetLength){
            if (string[usedLength] == ' '){
                string[TargetLength--]= '0';
                string[TargetLength--] = '2';
                string[TargetLength--] = '%';
            }else {
                string[TargetLength--] = string[usedLength];

            }
            usedLength--;


        }
      System.out.println(string);
    }
    
    public static void main(String[] args) {
        char [] chars = new char[50];//定義char時必須初始化長度
        chars[0] = '0';
        chars[1] = '1';
        chars[2] = ' ';
        chars[3] = '3';
        chars[4] = ' ';
        chars[5] = '5';
        chars[6] = '6';
        System.out.println(chars);
        replaceblank(chars,7);

    }
}

拓展:本題可以有很多拓展的地方,比如,輸入數據校驗,如果長度爲0,返回-1;沒有空格,則不處理;可以再進行優化。

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