一道C++练习题,替换一个字符串里所有实例

时间:2022-01-02 15:00:25

做了一道C++练习题,替换一个字符串里面的所有实例。

#include <iostream>
#include <string>
using namespace std;

const int NOT_FOUND = -1;
int strFind(string str, string strSub);
string strRepIdx(string strDes, int idxStart, int idxEnd, string strRepDes);
string strRep(string strDes, string strRepSrc, string strRepDes);

// Replace all instances of strRepSrc in strDes with strRepDes and return the string replaced;
string strRep(string strDes, string strRepSrc, string strRepDes)
{
int nIdxFound = strFind(strDes, strRepSrc);
if (NOT_FOUND == nIdxFound)
{
return strDes;
}
else
{
string strLeft = strDes.substr(nIdxFound+ strRepSrc.length(),strDes.length()-nIdxFound);
string strTemp = strRepIdx(strDes, nIdxFound, nIdxFound + strRepSrc.length()-1, strRepDes);
return strTemp.substr(0, nIdxFound + strRepDes.length()) + strRep(strLeft,strRepSrc,strRepDes);

}
return strDes;
}

// find index of substring strSub in string str;
// return:
//-1,for not found
//0 or positive int, index of substring
int strFind(string str, string strSub)
{
int strLen = str.length();
int subStrLen = strSub.length();
if (strLen < subStrLen)
{
return NOT_FOUND;
}
else
{
for (int i = 0; i < strLen - subStrLen+1; i++)
{
if (str.substr(i, subStrLen) == strSub)
{
return i;
}
}
}
return NOT_FOUND;
}

string strRepIdx(string strDes, int idxStart, int idxEnd, string strRepDes)
{
strDes = strDes.substr(0, idxStart) + strRepDes + strDes.substr(idxEnd+1, strDes.length());
return strDes;
}

int main()
{
string str0 = "Hello World";
string subStr1 = "World";
string subStr2 = "l";
string subStrDes = "ii";

cout << "Origin String is " << str0 << endl;
cout << "Replace " << subStr1 << " with " << subStrDes << " is " << strRep(str0, subStr1, subStrDes) << endl;
string strRep2 = strRep(str0, subStr2, subStrDes);
cout << "Replace " << subStr2 << " with " << subStrDes << " is " << strRep2 << endl;

return 0;
}

感觉基础的编码水平还基本停留在大一学C语言时候……┗|`O′|┛ 。