剑指Offer 替换空格

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
思路:
替换空格,先遍历一遍记录字符串中空格数量,算出替换后字符串长度,从后往前替换。
 
 1 //length为牛客系统规定字符串输出的最大长度,固定为一个常数
 2 class Solution {
 3 public:
 4     void replaceSpace(char *str,int length) {
 5         int i,p,q;
 6         int oldCount,spaceCount;
 7         
 8         i=oldCount=spaceCount=0;
 9         
10         while(str[i]!='')
11         {
12             oldCount++;
13             if(str[i]==' ')
14                 spaceCount++;
15             i++;            
16         }
17         int newLength=oldCount+spaceCount*2;
18                 
19         p=oldCount;
20         q=newLength;
21                 
22         while(p>=0)
23         {
24             if(str[p]==' ')
25             {
26                 str[q--]='0';
27                 str[q--]='2';
28                 str[q--]='%';                
29             }
30             else
31                 str[q--]=str[p];
32             
33             p--;
34         }
35     }
36 };
原文地址:https://www.cnblogs.com/SeekHit/p/5755997.html