牛客66题(2)替换空格

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

class Solution {
public:
	void replaceSpace(char *str,int length) {    
 if (str==NULL||length<0)
    return;
       int orgial=0;int blank=0;int i;
       for (i=0;str[i]!='\0';i++)
       {
            orgial++;
            if(str[i]==' ')
               blank++;
        }
        int neworgial=orgial+blank*2;
  int porgial=orgial;//原串长度
  int  pneworgial=neworgial;//目标串长度
while(porgial<pneworgial && porgial>=0)
    {
     if(str[porgial]==' ')
       {   str[pneworgial--]='0';
          str[pneworgial--]='2';
         str[pneworgial--]='%';
    }
      else 
      {str[pneworgial--]=str[porgial];}
        porgial--;
   }
   }
};

总结:(1)先用for循环求出字符串长度与字符串中空格的个数

(2)因为替换空格成3个空间,则计算新串的长度

(3)while循环内部用判断,从末尾往前搜索原串空格,如果搜索到空格,在新串位置填入替换值,如果不是空格,直接递减将原串的值赋值给新串位置。

猜你喜欢

转载自blog.csdn.net/libinxxx/article/details/84380634