題目描述:
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
代碼:
public String replaceSpace(StringBuffer str) {
int length = str.length();
int num = 0;
for (int i = 0; i < length; i++) {
if(str.charAt(i) == ' ')
num++;
}
int newLength = length + num * 2;
str.setLength(newLength);
int index = length - 1;
int newIndex = newLength - 1;
for (int i = index; i >= 0; i--) {
if(str.charAt(i) == ' '){
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
}else{
str.setCharAt(newIndex--, str.charAt(i));
}
}
return str.toString();
}