剑指5:替换空格

剑指Offer(二):替换空格

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

class Solution {
public:
	void replaceSpace(char *str,int length) {
        int oldlengh=0,numberofblank=0;
        for(int i =0;str != nullptr && length >0 && str[i]!= '\0';i++)
        {
            oldlengh++;//原始整个语句的length,包括空格
            if(str[i] == ' ') numberofblank++;//赋值和判断的区别要注意!!!之前=为赋值,条件必定为真,所以空格数即oldlengh数,错误结果%20%20%20%20%20%20%20%20%20%20%20
        }
        int newlengh = oldlengh + numberofblank *2;
        if(newlengh > length) return;
        while(oldlengh >= 0 && newlengh > oldlengh)
        {
            if(str[oldlengh] != ' ')
            {
                str[newlengh] = str[oldlengh];
                oldlengh--;
                newlengh--;
            }
            else if(str[oldlengh] == ' ')
            {
                str[newlengh--] = '0';
                str[newlengh--] = '2'; 
                str[newlengh--] = '%'; 
                oldlengh--;
            }
        }

	}
};

猜你喜欢

转载自blog.csdn.net/starluqifei/article/details/88304016