Example #1
0
// Заменить в строке Str Count вхождений подстроки FindStr на подстроку ReplStr
// Если Count < 0 - заменять "до полной победы"
// Return - количество замен
int ReplaceStrings(string &strStr,const wchar_t *FindStr,const wchar_t *ReplStr,int Count,BOOL IgnoreCase)
{
	const int LenFindStr=StrLength(FindStr);
	if ( !LenFindStr || !Count )
		return 0;
	const int LenReplStr=StrLength(ReplStr);
	size_t L=strStr.GetLength();

	const int Delta = LenReplStr-LenFindStr;
	const int AllocDelta = Delta > 0 ? Delta*10 : 0;

	size_t I=0;
	int J=0;
	while (I+LenFindStr <= L)
	{
		int Res=IgnoreCase?StrCmpNI(&strStr[I], FindStr, LenFindStr):StrCmpN(&strStr[I], FindStr, LenFindStr);

		if (!Res)
		{
			wchar_t *Str;
			if (L+Delta+1 > strStr.GetSize())
				Str = strStr.GetBuffer(L+AllocDelta);
			else
				Str = strStr.GetBuffer();

			if (Delta > 0)
				wmemmove(Str+I+Delta,Str+I,L-I+1);
			else if (Delta < 0)
				wmemmove(Str+I,Str+I-Delta,L-I+Delta+1);

			wmemcpy(Str+I,ReplStr,LenReplStr);
			I += LenReplStr;

			L+=Delta;
			strStr.ReleaseBuffer(L);

			if (++J == Count && Count > 0)
				break;
		}
		else
		{
			I++;
		}
	}

	return J;
}