剑指offer---替换空格

题目:替换空格

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

1 class Solution {
2 public:
3     void replaceSpace(char *str,int length) {
4 
5     }
6 };

解题代码:

 1 class Solution {
 2 public:
 3     void replaceSpace(char *str,int length) {
 4         if(str == nullptr || length <= 0)
 5             return ;
 6 
 7         int origLength = 0;
 8         int numBlank = 0;
 9         int i = 0;
10         while(str[i] != '\0'){
11             if(str[i] == ' ')
12                 numBlank++;
13             origLength++;
14             i++;
15         }
16 
17         int newLength = origLength + 2 * numBlank;
18         if(newLength > length)
19             return ;
20 
21         int pOld = origLength;
22         int pNew = newLength;
23         while(pOld>=0 && pOld<pNew){
24             if(str[pOld] != ' ')
25                 str[pNew--] = str[pOld];
26             else{
27                 str[pNew--] = '0';
28                 str[pNew--] = '2';
29                 str[pNew--] = '%';
30             }
31             pOld--;
32         }
33     }
34 };

 

posted on 2018-10-24 09:19  wangzhch  阅读(200)  评论(0编辑  收藏  举报

导航