請實現一個函數,將一個字符串中的每一個空格替換成「%20」。例如,當字符串爲We Are Happy.則通過替換以後的字符串爲We%20Are%20Happy。web
兩種寫法,一種是用Stringbuffer,只需遍歷一次,但返回時要複製一份字符串;另外一種是用字符數組,缺點是要遍歷兩次。數組
一、Stringbufferapp
注意Stringbuffer的用法和源碼svg
public class Solution { public String replaceSpace(StringBuffer str) { StringBuffer res = new StringBuffer(); for(int i=0; i<str.toString().length(); i++) { if(str.charAt(i) == ' '){ res.append("%20"); } else{ res.append(str.charAt(i)); } } return res.toString(); } }
public class ReplaceSpace { public void replceSpaces(char[] str, int length) { int spaceCount = 0; for(int i=0; i < length; i++) { if(str[i] == ' ') spaceCount++; } //System.out.println(spaceCount); int newLength = length + spaceCount * 2; str[newLength] = '\0'; newLength = newLength - 1; for(int i = length - 1; i >= 0; i--) { if(str[i] == ' ') { str[newLength--] = '0'; str[newLength--] = '2'; str[newLength--] = '%'; }else { str[newLength--] = str[i]; } } System.out.println(str); } public static void main(String[] args) { ReplaceSpace a = new ReplaceSpace(); char[] str = new char[20]; str[0] = ' '; str[1] = 'a'; str[2] = ' '; str[3] = 'b'; str[4] = 'c'; int length = 5; a.replceSpaces(str, length); } }