| 126 | } |
| 127 | |
| 128 | std::vector<StringPiece> SplitV2(const string& str, StringPiece sep, |
| 129 | int maxsplit) { |
| 130 | // This SplitV2 method matches the behavior of python's str.split: |
| 131 | // If sep is given, consecutive delimiters are not grouped together |
| 132 | // and are deemed to delimit empty strings (for example, '1,,2'.split(',') |
| 133 | // returns ['1', '', '2']). The sep argument may consist of multiple |
| 134 | // characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). |
| 135 | // Splitting an empty string with a specified separator returns ['']. |
| 136 | // |
| 137 | // If sep is not specified or is None, a different splitting algorithm is |
| 138 | // applied: runs of consecutive whitespace are regarded as a single |
| 139 | // separator, and the result will contain no empty strings at the start or |
| 140 | // end if the string has leading or trailing whitespace. Consequently, |
| 141 | // splitting an empty string or a string consisting of just whitespace |
| 142 | // with a None separator returns []. |
| 143 | |
| 144 | std::vector<StringPiece> result; |
| 145 | |
| 146 | StringPiece text(str); |
| 147 | if (maxsplit == 0) { |
| 148 | result.emplace_back(text); |
| 149 | return result; |
| 150 | } |
| 151 | |
| 152 | if (sep.empty()) { |
| 153 | StringPiece token; |
| 154 | // Remove leading whitespaces. |
| 155 | str_util::RemoveLeadingWhitespace(&text); |
| 156 | int split = 0; |
| 157 | while (str_util::ConsumeNonWhitespace(&text, &token)) { |
| 158 | result.push_back(token); |
| 159 | str_util::RemoveLeadingWhitespace(&text); |
| 160 | ++split; |
| 161 | if (maxsplit > 0 && split == maxsplit) { |
| 162 | result.push_back(text); |
| 163 | return result; |
| 164 | } |
| 165 | } |
| 166 | return result; |
| 167 | } |
| 168 | auto p = std::search(text.begin(), text.end(), sep.begin(), sep.end()); |
| 169 | int split = 0; |
| 170 | while (p != text.end()) { |
| 171 | StringPiece token = text.substr(0, p - text.begin()); |
| 172 | result.push_back(token); |
| 173 | text.remove_prefix(token.size()); |
| 174 | text.remove_prefix(sep.size()); |
| 175 | ++split; |
| 176 | if (maxsplit > 0 && split == maxsplit) { |
| 177 | result.push_back(StringPiece(text)); |
| 178 | return result; |
| 179 | } |
| 180 | p = std::search(text.begin(), text.end(), sep.begin(), sep.end()); |
| 181 | } |
| 182 | result.push_back(text); |
| 183 | return result; |
| 184 | } |
| 185 |
no test coverage detected