- 题目:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。完成代码:
public class Solution {
public String replaceSpace(StringBuffer str) {
}
}
- 思路1:直接用String的方法replace
- 思路2:遍历字符串StringBuffer,遇到空格就替换为“%20”
- Solution1:
public class Solution1 {
public String replaceSpace(StringBuffer str) {
if(null==str){
return null;
}else {
return str.toString().replace(" ","%20");
}
}
}
public class Solution2 {
public String replaceSpace(StringBuffer str) {
StringBuilder stringBuilder = new StringBuilder();
if (null == str) {
return null;
} else {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
stringBuilder.append("%20");
} else {
stringBuilder.append(c);
}
}
return stringBuilder.toString();
}
}
}