替換字串中的空格為%20
阿新 • • 發佈:2019-01-31
劍指offer上面的一道題。例如字串是we are happy.
輸出 we%20are%20happy.
如果按照基本的思路從前到後遍歷字串,每次識別到空格後面的字元就要往後移動兩個位。因此用從後向前的方式
先計算出替換後的陣列的長度。設定兩個指標一個指向新陣列的尾部,另一個指向原來陣列的尾部。直到兩個指標的數值相同時表示遍歷完成。
程式碼如下。
#include<stdlib.h> #include<iostream> #include<stdio.h> #include<vector> #include<cmath> #include<string.h> using namespace std; void replaceblank(char string[],int length) { int space=0; int nospace=0; int i=0; int reallength=0; if(string==null&&length<=0) return; while(string[i]!='\0') { reallength++; if(string[i]==' ') space++; else nospace++; i++; } int newlength=reallength+space*2; int a=reallength; int b=newlength; while(b>a) { if(string[a] == ' ') { string[b--]='0'; string[b--]='2'; string[b--]='%'; a--; } else { string[b--]=string[a--]; } } } int main() { char string[18]={"we are happy"}; replaceblank(string,18); cout<<string<<endl; }