思路
- 字符串转为char数组(注意api是toCharArray)
- 遍历数组,遇到空格' '转成%20追加到字符串中(' '占一位,%20占三位)
public String replaceSpace(String s) {
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < chars.length;i++ ) {
if(' ' == chars[i])
sb.append("%20");
else
sb.append(chars[i]);
}
return sb.toString();
}
解法2
- 直接替换就好
return s.replace(" ","%20");
Q.E.D.