牛客66題(2)替換空格
阿新 • • 發佈:2018-11-24
請實現一個函式,將一個字串中的每個空格替換成“%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迴圈內部用判斷,從末尾往前搜尋原串空格,如果搜尋到空格,在新串位置填入替換值,如果不是空格,直接遞減將原串的值賦值給新串位置。