问题
用C++写一个小程序,先请用户输入3个字符串,然后把在第一个字符串中出现的所有第2个字符串替换成第3个字符串,最后输出新的字符串;
代码
#include <iostream>
using namespace std;
char *replace(const char *str,const char *sub1,const char *sub2,char *output)
{
char *pOutput = NULL;
const char *pStr = NULL;
int lensub1 = strlen(sub1);
int lensub2 = strlen(sub2);
pOutput = output;
pStr = str;
while(*pStr!=0)
{
pStr = strstr(pStr,sub1);//在str中寻找sub1子串
if(NULL!= pStr) //找到sub1子串
{
memcpy(pOutput,str,pStr-str);
pOutput+=pStr-str;
memcpy(pOutput,sub2,lensub2);
pOutput+=lensub2;
pStr += lensub1;
str = pStr;
}
else
{
break;
}
}
*pOutput ='\0';
if(*str != '\0')
{
strcpy(pOutput,str);
}
return output;
}
int main()
{
char str[50] ="";
char sub1[10] = "";
char sub2[10] = "";
char output[100] = "";
cout<<"str: ";
cin>>str;
cout<<"sub1: ";
cin>>sub1;
cout<<"sub2: ";
cin>>sub2;
cout<<replace(str,sub1,sub2,output)<<endl;
return 0;
}