LeetCode 替换空格 [简单]
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
题目分析
解法1
使用Java的String的API String().replace("","");
解法2
将字符串转化为字符数组,然后遍历。符合条件则直接加入即可
代码实现
public class ReplaceSpace {
public static void main(String[] args) {
String s = "We are happy.";
String s2 = "We are happy.";
System.out.println(replaceSpace(s));
System.out.println(replaceSpace2(s2));
}
public static String replaceSpace2(String s) {
if (s == null || s.length() == 0) {
return "";
}
int len = s.length();
char[] array = new char[len * 3];
int size = 0;
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c == ' ') {
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
} else {
array[size++] = c;
}
}
return new String(array, 0, size);
}
public static String replaceSpace(String s) {
return s.replace(" ", "%20");
}
}