成都创新互联网站制作重庆分公司

【字符串】替换空格

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

using namespace std;

class Solution {
public:
    void replaceSpace(char *str, int length) {
        for (int i = 0; i < length; ++i){
            if (*(str + i) == ' '){
                length += 2;
                memset(str + length-2, 0, 2);
                for (int j = length-1; j > i; --j){
                    *(str + j) = *(str + j - 2);
                }
                *(str + i) = '%';
                *(str + i + 1) = '2';
                *(str + i + 2) = '0';
                ++i;
                ++i;
            }
        }
        *(str + length) = '\0';
    }
};

void foo()
{
    char str[100] = "We Are Happy";
    int len = strlen(str);
    Solution sol;
    sol.replaceSpace(str, len);
    cout << str << endl;
    //如果返回时,str数组长度出现了变化,就会出现Stack around the variable 'str' was corrupted
}

int main()
{
    foo();
    return EXIT_SUCCESS;
}

当前文章:【字符串】替换空格
当前地址:http://cxhlcq.com/article/gjecdc.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部