题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
代码示例
public class Offer4 {
public static void main(String[] args) {
Offer4 testObj = new Offer4();
StringBuffer sb = new StringBuffer("hello world");
System.out.println(testObj.replaceSpace(sb));
}
public String replaceSpace(StringBuffer str) {
int beforeLength = str.length() - 1;
for (int i = 0; i <= beforeLength; i++) {
if (str.charAt(i) == ' ') {
str.append(" ");//添加两个空格
}
}
int afterLength = str.length() - 1;
while (afterLength > beforeLength && beforeLength >= 0) {
char ch = str.charAt(beforeLength--);
if (ch == ' ') {
str.setCharAt(afterLength--, '0');
str.setCharAt(afterLength--, '2');
str.setCharAt(afterLength--, '%');
} else {
str.setCharAt(afterLength--, ch);
}
}
return str.toString();
}
}