问题:将字符串中所有空格替换为20%
思路:遍历字符串,统计空格数。根据空格数开辟空间,引入两个指针p1,p2,p1指向字符串结尾部分,p2指向开辟空间后的尾部;将p1指向的字符复制到p2处,遇到空格用20%替换。
为了便于显示空格表示为‘-’
#include <iostream>
#include <string.h>
using namespace std;
void replaceWith(char * s,int lenght)
{
if(s==NULL)
return;
int spaceNum=0;
int p1,p2,newLength;
//统计空格数
for(int i=0;i<strlen(s);i++)
{
if(s[i]=='-')
{
spaceNum++;
}
}
newLength=strlen(s)+2*spaceNum;
//如果s空间小于被替换所需长度,返回
if(newLength>lenght)
return;
//从后面开始移动字符串进行替代
p2=newLength;
p1=strlen(s);
while(p1<p2)
{
if(s[p1]=='-')
{
s[p2--]='%';
s[p2--]='0';
s[p2--]='2';
p1--;
}
else
{
s[p2--]=s[p1--];
}
}
}
int main()
{
char a[100]="How-are-you?";
char b[100]="The-cat-is-so-cute-that-i-like-it-so-much.";
replaceWith(a,100);
replaceWith(b,100);
cout<<a<<endl;
cout<<b<<endl;
return 0;
}
输出结果:
How20%are20%you?
The20%cat20%is20%so20%cute20%that20%i20%like20%it20%so20%much.