这个需要注意的是字符串的结尾最后一个字符为'\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; }
运行结果: