Closed alexey-malov closed 8 years ago
#define NORMALIZE_ARRAY_INDEX_VALUE 1
#define ADDITIONAL_INDEX_FOR_ENDL 1
const char* doReplace(const string& inputLine, const string& searchString, const string& replaceString)
{
vector<int> replacePositions;
replacePositions = findReplacePositions(inputLine, searchString);
if (replacePositions.empty())
{
return inputLine.c_str();
}
size_t inputLinePos = 0;
size_t newLineLength = inputLine.length() + (replaceString.length() - searchString.length()) * replacePositions.size();
char* newLine = new char[newLineLength + ADDITIONAL_INDEX_FOR_ENDL];
char* newLineCopyPositionPtr = newLine;
size_t countCharToCopy;
for (auto nextReplacementPosition : replacePositions)
{
countCharToCopy = nextReplacementPosition - inputLinePos;
inputLine.copy(newLineCopyPositionPtr, countCharToCopy, inputLinePos);
inputLinePos += countCharToCopy;
newLineCopyPositionPtr += countCharToCopy;
replaceString.copy(newLineCopyPositionPtr, replaceString.length(), 0);
inputLinePos += searchString.length();
newLineCopyPositionPtr += replaceString.length();
}
if (inputLinePos != inputLine.length())
{
countCharToCopy = inputLine.length() - inputLinePos + NORMALIZE_ARRAY_INDEX_VALUE;
inputLine.copy(newLineCopyPositionPtr, countCharToCopy, inputLinePos);
}
newLine[newLineLength] = '\0';
return newLine;
}
Используйте строки
vector<int> findReplacePositions(const string& source, const string& searchString)
используйте vector<size_t>