您的位置:首页 > 其它

把字符串中的空格替换为"%20"

2014-03-04 20:57 190 查看
这个需要注意的是字符串的结尾最后一个字符为'\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;

}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐