空格替换

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

class Solution {
public:
	void replaceSpace(char *str,int length) {
        if (str == NULL || length <= 0) {
            return;
        }
        //count
        int spaceCnt = 0, size = 0;
        for (int i = 0; str[i] != '\0'; i++) {
            if (str[i] == ' ') {
                spaceCnt++;
            }
            size++;
        }
        int newSize = size+2*spaceCnt;
        if (newSize > length) {
            return;
        }
        //from back to front
        for (int i = size, j = newSize; i >= 0; i--) {
            if (str[i] != ' ') {
                str[j--] = str[i];
            } else {
                str[j--] = '0';
                str[j--] = '2';
                str[j--] = '%';
            }
        }
	}
};



posted @ 2018-09-12 17:38  Spground  阅读(107)  评论(0编辑  收藏  举报