字符串中的每个空格替换成“%20”

替换空格

http://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423

solution 1:

public class Solution {
    public String replaceSpace(StringBuffer str) {
        return str.toString().replace(" ", "%20");
    }
}

solution 2:

public String replace(StringBuffer str) {
        int n = str.length();
        for(int i=0; i<n; i++) {
            if(str.charAt(i) == ' ') {
                n += 2;
                str.replace(i, i+1, "%20");
            }
        }
        return str.toString();
    }

C++ solution:

class Solution {
public:
    void replaceSpace(char* str, int length) {
        string str_cpp(str);
        string::size_type pos = 0;
        while ((pos = str_cpp.find(' ')) != string::npos) {
            str_cpp.replace(pos, 1, "%20");
        }
        str = strcpy(str,str_cpp.c_str());
    }
};
全部评论
一行代码NBNB
点赞 回复 分享
发布于 2020-03-28 09:55
为什么要用StringBuffer,有什么原因吗?
点赞 回复 分享
发布于 2019-11-03 19:37

相关推荐

机械打工仔:有说的你怀疑一下就行了,直接问也太实诚了
点赞 评论 收藏
分享
评论
10
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务