leetcode 链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

题目

image.png

解法

  1. 直接使用内置函数:replace()

    1. class Solution {
    2. public String replaceSpace(String s) {
    3. String ans = s.replace(" ","%20");
    4. return ans;
    5. }
    6. }
  2. 字符替换

    1. class Solution {
    2. public String replaceSpace(String s) {
    3. if(s==null){
    4. return null;
    5. }
    6. char[] cbuf = s.toCharArray();
    7. StringBuilder ans=new StringBuilder();
    8. for(char c:cbuf){
    9. if(c==' '){
    10. ans.append("%20");
    11. }else{
    12. ans.append(c);
    13. }
    14. }
    15. return ans.toString();
    16. }
    17. }