- 題目:請實現一個函數,將一個字符串中的每一個空格替換成「%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();
}
}
}
複製代碼