我並沒用到lengh引數,首選算出有多少個空格,然後構造新的陣列,主要為了解決空間問題。然後查到到空格的位置並將之後的元素都向後移動兩個元素,原來的查詢跳3步,如果沒找到空格跳1步下標。最後就找到空格,依次插入%20即可。
public
static string replacespace(string inistring, int length)
}//重新初始化陣列,每多乙個空格要多開闢兩個空間
char newarray = new
char[chararray.length + count * 2];
//賦值
for(int i = 0;i < chararray.length;i ++)
//移動並插入
for(int i = 0;i < newarray.length;)
i += 3;
}else
}//空間已經滿足條件
//準備插入
//轉換成char陣列
char carray = inistring.tochararray();
//定義乙個stringbuffer用來拼接
stringbuffer sb = new stringbuffer();
//定義乙個有沒壓縮的布林變數,預設為沒壓縮
boolean issub = false;
for (int i = 0,count = 1; i < carray.length;) }}
//拼接數字,並將外層迴圈跳到下乙個不同的字元上去
if(count != 1)
else
}//判斷布林並返回
return issub?sb.tostring() : inistring;
字串替換空格
點 抽象問題簡化問題 題意 乙個字串,比如 aaa baea erwe dsa dsa f a 替換其中的空格字元為 20 劍指offer面試題4 思路 這個問題的點在於,如果正常從頭到尾替換的話,每乙個被替換空格,它後面的全部字串都需要做整體移動 所以要設法想出,怎麼能夠減少字串移動 非空格字元需...
替換空格(字串)
思路一 利用string類的replaceall方法 public class solution 思路二 將字串轉換為字元陣列 建立乙個新的stringbuffer的物件,遍歷字元陣列,將不為空格的字元直接存入 當遇到空格時,存入 20 public class solution return st...
字串 替換空格
方法 從後往前替換,先求出字串總長度 空格數 新字串長度,然後兩個指標分別指向原始字串末尾和新字串末尾,依次替換,遇到空格時則替換為 0 2 include includevoid replaceblank char string,int length int newlength originall...