/**
* @Class ReplaceSpace
* @Description 剑指 Offer 05. 替换空格
* 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
* <p>
* 示例 1:
* 输入:s = "We are happy."
* 输出:"We%20are%20happy."
* <p>
* 限制:
* 0 <= s 的长度 <= 10000
* @Author
* @Date 2020/6/28
**/
public class ReplaceSpace {
}
// 简单方式直接字符串替换
public static String replaceSpace(String s) {
if (s == null || s.length() == 0) return s;
StringBuilder ans = new StringBuilder("");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == ' ') {
ans.append("%20");
} else ans.append(ch);
}
return ans.toString();
}
/**
* java 中没有结束符,是通过s.length 来找到字符串结尾的,redis的sds 也是通过length属性找到字符串结尾
*/
/* public static String replaceSpace(String s) {
if (s == null || s.length() == 0) return s;
char[] chs = new char[s.length() * 3 + 1];
int pos = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch != ' ') chs[pos++] = ch;
else {
chs[pos++] = '%';
chs[pos++] = '2';
chs[pos++] = '0';
}
}
chs[pos] = ' ';
return String.valueOf(chs);
}*/
// 测试用例
public static void main(String[] args) {
String s = " We are happy.";
String ans = replaceSpace(s);
System.out.println("demo01 result:" + ans);
}