1. question: 替换空格(简单)
请实现一个函数,把字符串 s 中的每个空格替换成”%20”。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
示例 1:
1 2
| 输入:s = "We are happy." 输出:"We%20are%20happy."
|
限制:
2. answers
这道题没什么可说的,遍历替换即可。代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class Solution_0034 {
public static String replaceSpace(String s) {
StringBuilder sb = new StringBuilder();
char[] chars = s.toCharArray();
for(char c: chars) { if(c == ' ') { sb.append("%20"); } else { sb.append(c); } }
return sb.toString(); }
public static void main(String[] args) { System.out.println();
String s = "We are happy.";
String result = replaceSpace(s);
System.out.println(result); } }
|
3. 备注
参考力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com),代码随想录 (programmercarl.com)。