替换空格
题目:请实现一个函数,把字符串中的每个空格替换成"%20",例如“We are happy.”,则输出“We%20are%20happy.”。
直接使用StringBuilder,从前往后遍历字符串的字符,如果是空格,StringBuilder就append%
,2
,0
,否则直接append 字符。
public String replaceSpace(String s) {
if (s == null) {
return null;
}
StringBuilder stringBuilder = new StringBuilder();
int lastIndex = s.length() - 1;
for (int i = 0; i <= lastIndex; i++) {
char charAt = s.charAt(i);
if (charAt == ' ') {
stringBuilder.append('%');
stringBuilder.append('2');
stringBuilder.append('0');
} else {
stringBuilder.append(charAt);
}
}
return stringBuilder.toString();
}
参考链接:
网友评论