1. 程式人生 > >【劍指offer】請實現一個函式,將一個字串中的每個空格替換

【劍指offer】請實現一個函式,將一個字串中的每個空格替換

劍指offer

題目如下

請實現一個函式,將一個字串中的每個空格替換成"%20"。
例如,當字串為We Are Happy,
則經過替換後的字串為 We%20Are%20Happy。

具體的程式碼實現如下

1.遍歷實現

public class Solution {
    /**
     * 	替換空格
     * 	問題描述:請實現一個函式,將一個字串中的每個空格替換成"%20"。
     *  例如,當字串為We Are Happy
     *  則經過替換後的字串為
     *  We%20Are%20Happy
     *
     */
    public
String replaceSpace(StringBuffer str){ String str1 = str.toString(); if(str1.equals("")){ return str1; } char[] strArray = str1.toCharArray(); int i = 0; int spaceLength = 0; //遍歷陣列中元素,記錄空格的數量 while(i < strArray.length){
if(strArray[i] == ' '){ spaceLength ++; } i++; } //建立新陣列,長度為原陣列+空格數量的2倍,以方便替換20%三個字元 int newStrLength = strArray.length + spaceLength * 2; char[] newStr = new char[newStrLength]; int k = strArray.length - 1 ;
int j = newStrLength - 1 ; //替換字元 while(k >= 0){ if(strArray[k] != ' ') { newStr[j--] = strArray[k--]; }else{ newStr[j--] = '0'; newStr[j--] = '2'; newStr[j--] = '%'; k--; } } return new String(newStr); } public static void main(String[] args) { Solution sl = new Solution(); StringBuffer str = new StringBuffer("We Are Happy"); System.out.println(sl.replaceSpace(str)); } }

2.利用API中的delete,append實現

public class Solution {
 
    public String replaceSpace(StringBuffer str) {
        String src = str.toString();
        str.delete(0, src.length());
        //清空陣列,便於新增
        char[] chars = src.toCharArray();
        for (char a : chars) {
            if (a == ' ') {
                str.append("%20");
            } else {
                str.append(a);
            }
        }
        return str.toString();
    }

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