title: '算法:替换空格' cover: https://img.paulzzh.com/touhou/random?3 date: 1996-07-27 00:00:03 categories: 算法题目 tags: [算法题目, 字符串]
<br/>
<!--more-->请实现一个函数,将一个字符串中的每个空格替换成“%20”
例如,当字符串为We Are Happy. 则经过替换之后的字符串为We%20Are%20Happy。
简单题目, 构建一个StringBuilder, 然后遍历字符串, 遇到空格则添加%20
即可
public class Solution {
public String replaceSpace(StringBuffer str) {
if (str == null) return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == ' ') {
sb.append("%20");
} else {
sb.append(c);
}
}
return sb.toString();
}
}