-
string str2 = “def”;string str1 = "abcdefghdef";
string str3 = “123456”;
题目大意就是把str1字符串里面的def都替换为123456。
(1)算法分析,我们可以充分利用string的函数库的作用。string的find函数可以找到def第一个存在的位置pos,那么我们可以知道0-pos是我们需要的字符串。0-pos之后我们可以加上str3的字符串。str1的pos+str.size()到末尾的子字符串为ghdef
再用上述方法处理即可。整体的代码实现如下:
#include
#include
using namespace std;
string stringReplace(string src, string &rep, string &dst)
{
string result = “”;
int i = 0;
while (src.find(rep) != string::npos)
{
auto pos = src.find(rep);
string str1 = src.substr(i, pos - i);
result = result + str1+dst;
src = src.substr(pos + rep.size());
}
return result;
}
int main()
{
string str1 = “abcdefghdef”;
string str2 = “def”;
auto pos=str1.find(str2);
cout << pos << endl;
int end=pos + str2.size()-1;
cout << str1.substr(pos+str2.size()) << endl;
string str3 = “123456”;
cout << stringReplace(str1, str2, str3) << endl;
system(“pause”);
return 0;
}
实现的了替换