替换空格
(java实现)
题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
示例1:
输入
We Are Happy
输出
We%20Are%20Happy
问题分析:
思路一:使用内置函数,进行替换;(但要注意,传入的参数为StringBuffer,需要先将其转为字符串);
思路二:拆分,后添加
相关知识:
略
参考代码:
思路一实现:
public class Solution { public String replaceSpace(StringBuffer str) { String res = str.toString(); res = res.replaceAll(" ","%20"); return res; } }
思路二实现:
public class Solution { public String replaceSpace(StringBuffer str) { if (str.length()<=0) return ""; String res = ""; for (int i=0; i<str.length(); i++) { if (' ' == str.charAt(i)) res += "%20"; else res += str.charAt(i); } /* //错误 String s = str.toString(); String[] st = s.split(" "); for (int i=0; i<st.length-1; i++) res = res + st[i] + "%20"; res += st[st.length-1]; */ return res; } }
测试用例
"hello world"
" helloworld"
"helloworld "
"hello world"
""
" "
"helloworld"
" "