* Split a string using separator `sep` * * @param sep the separator to split on * @param s the string to split * @param trim_segments if true, trim whitespace on the resulting segments. * Default: true * @param accept_empty_segments if true, allow length 0 segments. If false, * the separator characters around empty segments will be consumed, bu * the resulting vector w
| 541 | * @return a vector of the resulting segments after the split |
| 542 | */ |
| 543 | vector<string> split_string(const string &sep, string s, bool trim_segments, |
| 544 | bool accept_empty_segments, int nsplits, |
| 545 | bool ignore_escapes) |
| 546 | { |
| 547 | vector<string> segments; |
| 548 | int separator_length = sep.length(); |
| 549 | set<size_t> escapes; // annoying to have to always create... |
| 550 | if (ignore_escapes) |
| 551 | escapes = find_escapes(s); |
| 552 | |
| 553 | size_t pos = 0; |
| 554 | size_t original_pos = 0; // original position of s[0] |
| 555 | while (nsplits && (pos = s.find(sep, pos)) != string::npos) |
| 556 | { |
| 557 | if (escapes.count(pos + original_pos)) |
| 558 | { |
| 559 | ASSERT(pos > 0); // should be impossible for char 0 to be escaped |
| 560 | // erase the backslash |
| 561 | s.erase(pos - 1, 1); |
| 562 | original_pos++; |
| 563 | pos += separator_length - 1; |
| 564 | continue; |
| 565 | } |
| 566 | add_segment(segments, s.substr(0, pos), |
| 567 | trim_segments, accept_empty_segments); |
| 568 | |
| 569 | s.erase(0, pos + separator_length); |
| 570 | original_pos += pos + separator_length; |
| 571 | pos = 0; |
| 572 | |
| 573 | if (nsplits > 0) |
| 574 | --nsplits; |
| 575 | } |
| 576 | |
| 577 | // consume any escaped separators in the remainder; not a very elegant approach |
| 578 | if (ignore_escapes) |
| 579 | s = replace_all(s, make_stringf("\\%s", sep.c_str()), sep); |
| 580 | add_segment(segments, s, trim_segments, accept_empty_segments); |
| 581 | |
| 582 | return segments; |
| 583 | } |
| 584 | |
| 585 | string remove_prepended_the(string s) |
| 586 | { |
no test coverage detected