| 236 | // ---------------------------------------------------------------------- |
| 237 | |
| 238 | int GlobalReplaceSubstring(const StringPiece& substring, |
| 239 | const StringPiece& replacement, |
| 240 | string* s) { |
| 241 | CHECK(s != nullptr); |
| 242 | if (s->empty() || substring.empty()) |
| 243 | return 0; |
| 244 | string tmp; |
| 245 | int num_replacements = 0; |
| 246 | size_t pos = 0; |
| 247 | for (size_t match_pos = s->find(substring.data(), pos, substring.length()); |
| 248 | match_pos != string::npos; |
| 249 | pos = match_pos + substring.length(), |
| 250 | match_pos = s->find(substring.data(), pos, substring.length())) { |
| 251 | ++num_replacements; |
| 252 | // Append the original content before the match. |
| 253 | tmp.append(*s, pos, match_pos - pos); |
| 254 | // Append the replacement for the match. |
| 255 | tmp.append(replacement.begin(), replacement.end()); |
| 256 | } |
| 257 | // Append the content after the last match. If no replacements were made, the |
| 258 | // original string is left untouched. |
| 259 | if (num_replacements > 0) { |
| 260 | tmp.append(*s, pos, s->length() - pos); |
| 261 | s->swap(tmp); |
| 262 | } |
| 263 | return num_replacements; |
| 264 | } |
| 265 | |
| 266 | //--------------------------------------------------------------------------- |
| 267 | // RemoveStrings() |