标签:c++
请实现一个函数,把字符串中每个空格替换成“%20”。例如输入“we are happy.",则输出”we%20are%20happy.“。
创建一个新的字符串,传出,是一个比较好的思路。
#include <iostream>
#include <string>
using namespace std;
int change(char *str, char *out)
{
int i=0,j=0;
char *temp="%20";
if (str==NULL||out==NULL)
{
return 0;
}
while(str[i]!='\0')
{
if (!isspace(str[i]))
{
out[j]=str[i];
}
else
{
strcat(out,temp);
j+=2;
}
i++;
j++;
}
return 1;
}
//测试用例
int main()
{
char buf[100];
char s[100]={0};
gets(buf);
change(buf,s);
printf("%s\n",s);
return 0;
}如果要在原来字符串上做替换
//高效思路为从后往前替换。
int change(char str[],int length )
{//length为字符数组的总容量
int i=0;
int index,indexnew;
if (str==NULL||length<=0)
{
return 0;
}
/*字符串的实际长度*/
int len=strlen(str);
int numofbanks=0;
while(str[i]!='\0')
{
if (isspace(str[i]))
{
numofbanks++;
}
i++;
}
/*新字符串的长度*/
int newlen=len+2*numofbanks;
if (newlen>length)
{
return 0;
}
index=len;
indexnew=newlen;
while(index>=0)
{
if (isspace(str[index]))
{
str[indexnew--]='0';
str[indexnew--]='2';
str[indexnew--]='%';
}
else
{
str[indexnew--]=str[index];
}
--index;
}
return 1;
}//测试用例
int main()
{
char buf[100];
char s[100]={0};
gets(buf);
change(buf,100);
printf("%s\n",buf);
return 0;
}标签:c++
原文地址:http://blog.csdn.net/lsh_2013/article/details/45199515