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

做了一道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′|┛ 。 

转载于:https://www.cnblogs.com/spyplus/p/7554476.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值