| 8 | |
| 9 | namespace mllm { |
| 10 | inline std::vector<std::string> splitString(const std::string& s, const std::string& sep = "", int maxsplit = -1) { |
| 11 | std::vector<std::string> out; |
| 12 | if (maxsplit == 0) { |
| 13 | out.push_back(s); |
| 14 | return out; |
| 15 | } |
| 16 | |
| 17 | const char* p = s.data(); |
| 18 | const char* end = p + s.size(); |
| 19 | |
| 20 | if (sep.empty()) { |
| 21 | auto skip_space = [&]() { |
| 22 | while (p != end && std::isspace(static_cast<unsigned char>(*p))) ++p; |
| 23 | }; |
| 24 | skip_space(); |
| 25 | while (p != end) { |
| 26 | const char* start = p; |
| 27 | while (p != end && !std::isspace(static_cast<unsigned char>(*p))) ++p; |
| 28 | out.emplace_back(start, p); |
| 29 | if (maxsplit >= 0 && --maxsplit == 0) { |
| 30 | out.emplace_back(p, end); |
| 31 | return out; |
| 32 | } |
| 33 | skip_space(); |
| 34 | } |
| 35 | return out; |
| 36 | } |
| 37 | |
| 38 | if (sep.size() == 1) { |
| 39 | const unsigned char needle = static_cast<unsigned char>(sep[0]); |
| 40 | while (maxsplit != 0) { |
| 41 | const char* pos = reinterpret_cast<const char*>(std::memchr(p, needle, end - p)); |
| 42 | if (!pos) break; |
| 43 | out.emplace_back(p, pos); |
| 44 | p = pos + 1; |
| 45 | if (maxsplit > 0) --maxsplit; |
| 46 | } |
| 47 | } else { |
| 48 | const auto n = sep.size(); |
| 49 | while (maxsplit != 0) { |
| 50 | const char* pos = std::search(p, end, sep.begin(), sep.end()); |
| 51 | if (pos == end) break; |
| 52 | out.emplace_back(p, pos); |
| 53 | p = pos + n; |
| 54 | if (maxsplit > 0) --maxsplit; |
| 55 | } |
| 56 | } |
| 57 | out.emplace_back(p, end); |
| 58 | return out; |
| 59 | } |
| 60 | } // namespace mllm |