请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public class Solution {
public String replaceSpace(StringBuffer str) {
int spaceNum = 0;
for(int i=0;i<str.length();i++) {
if (str.charAt(i) == ' ') {
spaceNum++;
}
}
int oldlength = str.length();
int newlength = oldlength + spaceNum * 2;
str.setLength(newlength);
int oldindex = oldlength - 1;
int newindex = newlength - 1;
for (; oldindex >= 0; oldindex--) {
if (str.charAt(oldindex) == ' ') {
str.setCharAt(newindex--, '0');
str.setCharAt(newindex--, '2');
str.setCharAt(newindex--, '%');
} else {
str.setCharAt(newindex--, str.charAt(oldindex));
}
}
return str.toString();
}
}