Replace the first "old" pattern with the "new" pattern in a string
| 23 | |
| 24 | // Replace the first "old" pattern with the "new" pattern in a string |
| 25 | std::string ReplaceFirst( |
| 26 | const StringPiece& s, |
| 27 | const StringPiece& oldsub, |
| 28 | const StringPiece& newsub) |
| 29 | { |
| 30 | if (oldsub.empty()) |
| 31 | return s.as_string(); |
| 32 | |
| 33 | std::string res; |
| 34 | std::string::size_type pos = s.find(oldsub); |
| 35 | if (pos == std::string::npos) |
| 36 | { |
| 37 | return s.as_string(); |
| 38 | } |
| 39 | else |
| 40 | { |
| 41 | res.append(s.data(), pos); |
| 42 | res.append(newsub.data(), newsub.size()); |
| 43 | res.append(s.data() + pos + oldsub.size(), s.length() - pos - oldsub.size()); |
| 44 | } |
| 45 | return res; |
| 46 | } |
| 47 | |
| 48 | // Replace all the "old" pattern with the "new" pattern in a string |
| 49 | std::string ReplaceAll(const StringPiece& s, const StringPiece& oldsub, |