Bariskas / oop

Лабораторные по ООП 2 курс ИПС
0 stars 0 forks source link

Замечания по программе Replace #1

Closed alexey-malov closed 8 years ago

alexey-malov commented 8 years ago
vector<int> findReplacePositions(const string&, const string&);
const char* doReplace(const string&, const string&, const string&);
alexey-malov commented 8 years ago
#define NORMALIZE_ARRAY_INDEX_VALUE 1
#define ADDITIONAL_INDEX_FOR_ENDL 1
alexey-malov commented 8 years ago
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;
}

Используйте строки

alexey-malov commented 8 years ago
vector<int> findReplacePositions(const string& source, const string& searchString)

используйте vector<size_t>