剑指offer面试题4-- 替换空格

来源:互联网 发布:淘宝论坛帐号 编辑:程序博客网 时间:2024/05/16 05:05
#include <iostream>using namespace std;class Solution {public:    void replaceSpace(char *str, int length) {        if (NULL == str || length <= 0)        {            return;        }        int newLength = 0, oldLength = 0;;        int index = 0;        newLength = strlen(str);        oldLength = strlen(str);        while (str[index] != '\0')        {            if (str[index] == ' ')            {                newLength += 2;            }            index++;        }        if (newLength > length)        {            return;        }        while (oldLength >= 0)        {            if (str[oldLength] == ' ')            {                str[newLength--] = '0';                str[newLength--] = '2';                str[newLength] = '%';            }            else            {                str[newLength] = str[oldLength];            }            newLength--;            oldLength--;        }    }};int main(){    Solution s;    char str[100] = "we are happy.";    s.replaceSpace(str, 100);    cout << str << endl << "len" << strlen(str) << endl;;    system("PAUSE");    return 0;}
0 0