《劍指Offer》之字符串替換空格

//題目描述
//請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。

注:
本專欄裏面的核心代碼都是在牛客網劍指Offer在線測試通過,並且在VS2015環境下測試通過!

代碼如下所示:

#include<iostream>

using namespace std;

class Replace_Space{
public:
    void replacespace(char* str,int length) {
        int num_space = 0;
        int new_length = 0;
        int old_length = 0;
        for (int i = 0; i < strlen(str); i++) {
            if (str[i] == ' ') {
                num_space++;

            }
        }
        new_length = strlen(str) + num_space*2;
        cout << new_length << endl;
        old_length = strlen(str);
        for (old_length; old_length >=0;) {
            //if(str[j])
            if (str[old_length] == ' ') {
                str[new_length--] = '0';
                str[new_length--] = '2';
                str[new_length] = '%';
            }
            else{
                str[new_length] = str[old_length];
            }
            old_length--;
            new_length--;
        }
    }
};
int main(int argc, char** argv) {

    Replace_Space test;
    char str[100] = " helloworld";
    test.replacespace(str,100);
    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章