《剑指Offer》算法题——替换空格

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

class Solution {
public:
    void replaceSpace(char *str, int length) {
        int spacenum = 0;
        int i = 0;
        while (i<length)
        {
            if (str[i] == ' ')
                spacenum++;
            i++;
        }
        if (0 == spacenum)
        {
            return;
        }
        int newlength = length + 2 * spacenum;
        //str = (char*)realloc(str, newlength);
        length--;
        newlength--;
        while (length >= 0)
        {
            if (str[length] != ' ')
            {
                str[newlength--] = str[length];
            }
            else
            {
                str[newlength--] = '0';
                str[newlength--] = '2';
                str[newlength--] = '%';
                
            }
            length--;
        }
    }
};

void main()
{
    Solution s;
    //char *str = "Hello World and Bill Gates";//存放在.rdata中,不能修改,指针指向常量区
    //所以要用字符数组保存常量,这样存放在栈中,可以修改
    char str[] = " helloworld";//考虑没有空格的情况,考虑空格在第一个字符的情况
    s.replaceSpace(str,11);
    printf("%s", str);
    system("pause");

}

运行输出结果:

并通关:

注意,如果传入char *str = "Hello World and Bill Gates";这样定义的str,则会崩溃,原因如上所述:

 

posted @ 2016-03-31 19:07  _No.47  阅读(314)  评论(0编辑  收藏  举报