這個需要注意的是字符串的結尾最后一個字符為'\0',並不是空字符,復制時要一塊復制,算法思想就是先計算出字符串中總的空格數,然后
重新計算字符串的長度,由於"%20"為3個字符,比原來多2個,所以,字符串長度是原來字符串長度加上空格字符總數×2,就是新的字符串的長度。
代碼如下:
#include <iostream> #include <cstdlib> using namespace std; void strReplace(char str[],int length) { if(str==NULL||length<0) exit(-1); int blank=0; int nLength; for(int i=0;i<length;i++) { if(str[i]==' ') blank++; } nLength=length+blank*2; for(int j=length;j>=0;j--) { if(str[j]!=' ') { str[nLength]=str[j]; nLength--; } else { str[nLength--]='0'; str[nLength--]='2'; str[nLength--]='%'; } } } int main() { char str[13]="we are happy"; int length=13; cout<<"before replace: "; cout<<str<<endl; strReplace(str,13); cout<<"after replace: "; cout<<str<<endl; return 0; }
運行結果: