Write a method to replace all spaces in a string with ‘%20’.
先计算空格数量,然后malloc新的字符串,新的长度为len+2*spacesNum;
然后再遍历一遍即可。
char* replaceSpaces(char* str)
{
char *p = str;
int len=0,spaceNum=0;
while(*p)
{
len++;
if(*p==' ')
spaceNum++;
p++;
}
int newLen = len + spaceNum*2;
char newIndex=0;
char* newStr=(char*)malloc((len+2*spaceNum+1)*sizeof(char));
for(int i=0;i<len;i++)
{
if(str[i]==' ')
{
newStr[newIndex++]='%';
newStr[newIndex++]='2';
newStr[newIndex++]='0';
}
else
newStr[newIndex++]=str[i];
}
newStr[newIndex]='\0';
return newStr;
}
int main()
{
char s1[]=" ";
char s2[]="a bc d e";
char s3[]=" a bcd ";
cout << replaceSpaces(s1) << endl;
cout << replaceSpaces(s2) << endl;
cout << replaceSpaces(s3) << endl;
return 0;
}