As I see it, two checks are missing:
- If
endString is not found, - If
endString is found before startString, in this case, your substraction to compute the second parameter of replace() will result in a negative length which will overflow.
Also, you might want to return a boolean to check whether there was a match or not.
Try something like this instead:
static bool replaceString(string &input, const string &startString, const string &endString, const string &replacement) { size_t indexStart, indexEnd; indexStart = input.find(startString); if (indexStart == input.npos) { return false; } indexEnd = input.find(endString, indexStart); // Note the offset to start searching // after the start index if (indexEnd == input.npos) { return false; } input.replace(indexStart, indexEnd-indexStart, replacement); return true; }
Test program:
int main (int, char**) { string s ("abcdefghijklmnopqrstuvwxyz"); string start ("gh"); string end ("pq"); string replace ("GHIJKLMNO"); bool ok = replaceString(s, start, end, replace); std::cout << "1. found? " << ok << ", result: " << s << std::endl; start = "pq"; end = "de"; ok = replaceString(s, start, end, replace); std::cout << "2. found? " << ok << ", result: " << s << std::endl; return 0; }
Output:
1. found? true, result: abcdefGHIJKLMNOpqrstuvwxyz 2. found? false, result: abcdefGHIJKLMNOpqrstuvwxyz
endStringcan't be found?ifclause, immediately afterreplace, then working back from there. You're not showing us enough to help you. For example, it could be that your caller is providing a copy of the xml string so you're still not operating on the value you expect, or any of dozens of other trivial mistakes.