面试题4 替换空格

题目描述:

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

输入:

每个输入文件仅包含一组测试样例。
对于每组测试案例,输入一行代表要处理的字符串。

输出:

对应每个测试案例,出经过处理后的字符串。

样例输入:
We Are Happy
样例输出:
We%20Are%20Happy
 1 class Solution {
 2 public:
 3     void replaceSpace(char *str,int length) {
 4         if (str == NULL || length <= 0){
 5             return;
 6         }
 7         int originalLength = 0, newLength = 0, count = 0;
 8         for (int i = 0; str[i] != ''; i++){
 9             if (str[i] == ' ')
10                 count++;
11             originalLength++;
12         }
13         newLength = originalLength + count * 2;
14         if (newLength > length){
15             return;
16         }
17         int i = originalLength, j = newLength;
18         while(i >= 0 && j > i){
19             if (str[i] == ' '){
20                 str[j--] = '0';
21                 str[j--] = '2';
22                 str[j--] = '%';
23             }
24             else
25                 str[j--] = str[i];
26             i--;
27         }
28     }
29 };
原文地址:https://www.cnblogs.com/wanderingzj/p/5351818.html