首页 > 其他 > 详细

剑指offer--2.替换空格

时间:2019-03-19 18:38:02      阅读:136      评论:0      收藏:0      [点我收藏+]

 太久没用C了,C++string是以‘\0‘结尾,C总char*也是以‘\0‘结尾

但是用string.copy()方法得到的字符串并不是以‘\0结尾

----------------------------------------------------------------------------------------------

时间限制:1秒 空间限制:32768K 热度指数:871481
本题知识点: 字符串

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
#include <string.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
    void replaceSpace(char *str,int length) {
        string strr(str);
        int pos;
        while ((pos = strr.find(" ")) != -1) {
            strr = strr.erase(pos, 1);
            strr = strr.insert(pos, "%20");
        }
        strr.copy(str, strr.length());
//        strcpy(str,strr.c_str());
        str[strr.length()] = \0;
        cout<<str;
    }
};
int main()
{

    Solution demo;
    char s[] = "we are happy!";
    demo.replaceSpace(s, 13);
    return 0;
}

 

剑指offer--2.替换空格

原文:https://www.cnblogs.com/evidd/p/10560449.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!