【字符串】替換空格

/*
請實現一個函數,將一個字符串中的空格替換成“%20”。
例如,當字符串爲We Are Happy.則經過替換之後的字符串爲
We%20Are%20Happy。
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章