replace all occurrences of search in subject with replace and return new string
| 420 | |
| 421 | /// replace all occurrences of search in subject with replace and return new string |
| 422 | std::string ReplaceString(const std::string& subject, const std::string& search, const std::string& replace) { |
| 423 | // 'abc','a','ab' -> 'abbc' |
| 424 | // 'abc','ab','a' -> 'ac' |
| 425 | // 'aaa','a','aa' -> 'aaaaaa' |
| 426 | // '1| 2','| ','|' -> '1,2' |
| 427 | std::string result = subject; |
| 428 | size_t pos = 0; |
| 429 | size_t add = 0; |
| 430 | // avoid endless replace if replace contains search token |
| 431 | if (replace.find(search) != std::string::npos) { |
| 432 | add = replace.length(); |
| 433 | } |
| 434 | // replace loop |
| 435 | while ((pos = result.find(search, pos)) != std::string::npos) { |
| 436 | result.replace(pos, search.length(), replace); |
| 437 | pos += add; // set startpoint for next loop |
| 438 | } |
| 439 | return result; |
| 440 | } |
| 441 | |
| 442 | /// replace all occurrences of search in subject with replace |
| 443 | void ReplaceStringInPlace(std::string& subject, const std::string& search, const std::string& replace) { |
no outgoing calls
no test coverage detected