剑指offer -- 替换空格

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/86654095
  • 描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
  • 分析:将给定字符串中的空格替换为’%20’
  • 思路一:先统计给定字符串中的空格个数,然后从后向前遍历字符串,把每一个字符移动到他的最终位置上去,并对空格进行填充。
class Solution {
public:
	void replaceSpace(char *str,int length) {
        int count = 0;
        for (int i = 0; i < length; i++) {
            if (str[i] == ' ') count++;
        }
        for (int i = length - 1; i >= 0; i--) {
            if (str[i] != ' ') {
                str[i + 2 * count] = str[i];
            } else {
                count--;
                str[i + 2 * count] = '%';
                str[i + 1 + 2 * count] = '2';
                str[i + 2 + 2 * count] = '0';
            }
        }
	}
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/86654095