剑指offer——03替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
注意事项:
  《剑指offer》上的length为str的最大长度空间
  而牛客上的lenght为str的长度,包括了''
  
由于str为数组指针,故只能在原数组上修改,选用后替换法
 
 1 class Solution {
 2 public:
 3     void replaceSpace(char *str, int length) {
 4         if (str == nullptr || length <= 0)
 5             return;
 6         int strLen = 0, spaceNum = 0, newLenght = 0;
 7         for (strLen = 0; str[strLen] != ''; ++strLen)
 8             if (str[strLen] == ' ')
 9                 spaceNum++;
10         newLenght = strLen + spaceNum * 2;
11         for (int i = newLenght, j = strLen; i >= 0; --j)
12             if (str[j] == ' ')
13             {
14                 str[i--] = '0';
15                 str[i--] = '2';
16                 str[i--] = '%';
17             }
18             else
19                 str[i--] = str[j];
20     }
21 };
原文地址:https://www.cnblogs.com/zzw1024/p/11650760.html