剑指02替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return "%20".join(list(s.split(" ")))

public class Solution {
    public String replaceSpace(StringBuffer str) {
            StringBuffer out=new StringBuffer();
        for (int i=0;i<str.toString().length();i++){
            char b=str.charAt(i);
            if (String.valueOf(b).equals(" ")){
                out.append("%20");
            }else {
                out.append(b);
            }
        }
        return out.toString();
    }
}

class Solution {
public:
    void replaceSpace(char *str,int length) {

        int  count=0;
        for (int i=0;i<length;i++){
            if (str[i]==' ')
                count++;
        }
        for (int i=length-1;i>=0;i--){
            if (str[i]!=' ')
            {
                str[i+2*count]=str[i];
            }
            else {
                count--;
                str[i+2*count]='%';
                str[i+2*count+1]='2';
                str[i+2*count+2]='0';
            }
        }
    }
};

 

posted on 2020-07-18 07:23  滚雪球效应  阅读(110)  评论(0编辑  收藏  举报