用 %20 替换字符串中的空格
按照书中的算法,首先找到字符串中空格的数量,扩展字符串空间,然后在源字符串尾部设置一个标识head,在扩展后的字符床尾部设置一个标识last。若head处字符不等于空格,那么直接把该字符赋值给last,head、last同时向前移动一个位置;若head处字符等于空格,那么last处赋值为‘0’,last-1处赋值为‘2’,last-2处赋值为‘%’,head向前移动一个位置,last向前移动三个位置。直到head和last标示(指向)同一个位置为止。
public String replaceSpace(StringBuffer str) {
int spaceNumber = 0;
int head = str.length() - 1;
int last = 0;
if (str != null) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spaceNumber++;
str.append(new char[2]);
}
}
last = head + (2 * spaceNumber);
}
while (head < last) {
char temp = str.charAt(head);
if (temp != ' ') {
str.setCharAt(last, temp);
head--;
last--;
} else {
str.setCharAt(last, '0');
str.setCharAt(last - 1, '2');
str.setCharAt(last - 2, '%');
head--;
last -= 3;
}
}
return str.toString();
}