You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

str_split.h 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. //
  2. // Copyright 2017 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // -----------------------------------------------------------------------------
  17. // File: str_split.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // This file contains functions for splitting strings. It defines the main
  21. // `StrSplit()` function, several delimiters for determining the boundaries on
  22. // which to split the string, and predicates for filtering delimited results.
  23. // `StrSplit()` adapts the returned collection to the type specified by the
  24. // caller.
  25. //
  26. // Example:
  27. //
  28. // // Splits the given string on commas. Returns the results in a
  29. // // vector of strings.
  30. // std::vector<std::string> v = absl::StrSplit("a,b,c", ',');
  31. // // Can also use ","
  32. // // v[0] == "a", v[1] == "b", v[2] == "c"
  33. //
  34. // See StrSplit() below for more information.
  35. #ifndef ABSL_STRINGS_STR_SPLIT_H_
  36. #define ABSL_STRINGS_STR_SPLIT_H_
  37. #include <algorithm>
  38. #include <cstddef>
  39. #include <map>
  40. #include <set>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. #include "absl/base/internal/raw_logging.h"
  45. #include "absl/base/macros.h"
  46. #include "absl/strings/internal/str_split_internal.h"
  47. #include "absl/strings/string_view.h"
  48. #include "absl/strings/strip.h"
  49. namespace absl
  50. {
  51. ABSL_NAMESPACE_BEGIN
  52. //------------------------------------------------------------------------------
  53. // Delimiters
  54. //------------------------------------------------------------------------------
  55. //
  56. // `StrSplit()` uses delimiters to define the boundaries between elements in the
  57. // provided input. Several `Delimiter` types are defined below. If a string
  58. // (`const char*`, `std::string`, or `absl::string_view`) is passed in place of
  59. // an explicit `Delimiter` object, `StrSplit()` treats it the same way as if it
  60. // were passed a `ByString` delimiter.
  61. //
  62. // A `Delimiter` is an object with a `Find()` function that knows how to find
  63. // the first occurrence of itself in a given `absl::string_view`.
  64. //
  65. // The following `Delimiter` types are available for use within `StrSplit()`:
  66. //
  67. // - `ByString` (default for string arguments)
  68. // - `ByChar` (default for a char argument)
  69. // - `ByAnyChar`
  70. // - `ByLength`
  71. // - `MaxSplits`
  72. //
  73. // A Delimiter's `Find()` member function will be passed an input `text` that is
  74. // to be split and a position (`pos`) to begin searching for the next delimiter
  75. // in `text`. The returned absl::string_view should refer to the next occurrence
  76. // (after `pos`) of the represented delimiter; this returned absl::string_view
  77. // represents the next location where the input `text` should be broken.
  78. //
  79. // The returned absl::string_view may be zero-length if the Delimiter does not
  80. // represent a part of the string (e.g., a fixed-length delimiter). If no
  81. // delimiter is found in the input `text`, a zero-length absl::string_view
  82. // referring to `text.end()` should be returned (e.g.,
  83. // `text.substr(text.size())`). It is important that the returned
  84. // absl::string_view always be within the bounds of the input `text` given as an
  85. // argument--it must not refer to a string that is physically located outside of
  86. // the given string.
  87. //
  88. // The following example is a simple Delimiter object that is created with a
  89. // single char and will look for that char in the text passed to the `Find()`
  90. // function:
  91. //
  92. // struct SimpleDelimiter {
  93. // const char c_;
  94. // explicit SimpleDelimiter(char c) : c_(c) {}
  95. // absl::string_view Find(absl::string_view text, size_t pos) {
  96. // auto found = text.find(c_, pos);
  97. // if (found == absl::string_view::npos)
  98. // return text.substr(text.size());
  99. //
  100. // return text.substr(found, 1);
  101. // }
  102. // };
  103. // ByString
  104. //
  105. // A sub-string delimiter. If `StrSplit()` is passed a string in place of a
  106. // `Delimiter` object, the string will be implicitly converted into a
  107. // `ByString` delimiter.
  108. //
  109. // Example:
  110. //
  111. // // Because a string literal is converted to an `absl::ByString`,
  112. // // the following two splits are equivalent.
  113. //
  114. // std::vector<std::string> v1 = absl::StrSplit("a, b, c", ", ");
  115. //
  116. // using absl::ByString;
  117. // std::vector<std::string> v2 = absl::StrSplit("a, b, c",
  118. // ByString(", "));
  119. // // v[0] == "a", v[1] == "b", v[2] == "c"
  120. class ByString
  121. {
  122. public:
  123. explicit ByString(absl::string_view sp);
  124. absl::string_view Find(absl::string_view text, size_t pos) const;
  125. private:
  126. const std::string delimiter_;
  127. };
  128. // ByChar
  129. //
  130. // A single character delimiter. `ByChar` is functionally equivalent to a
  131. // 1-char string within a `ByString` delimiter, but slightly more efficient.
  132. //
  133. // Example:
  134. //
  135. // // Because a char literal is converted to a absl::ByChar,
  136. // // the following two splits are equivalent.
  137. // std::vector<std::string> v1 = absl::StrSplit("a,b,c", ',');
  138. // using absl::ByChar;
  139. // std::vector<std::string> v2 = absl::StrSplit("a,b,c", ByChar(','));
  140. // // v[0] == "a", v[1] == "b", v[2] == "c"
  141. //
  142. // `ByChar` is also the default delimiter if a single character is given
  143. // as the delimiter to `StrSplit()`. For example, the following calls are
  144. // equivalent:
  145. //
  146. // std::vector<std::string> v = absl::StrSplit("a-b", '-');
  147. //
  148. // using absl::ByChar;
  149. // std::vector<std::string> v = absl::StrSplit("a-b", ByChar('-'));
  150. //
  151. class ByChar
  152. {
  153. public:
  154. explicit ByChar(char c) :
  155. c_(c)
  156. {
  157. }
  158. absl::string_view Find(absl::string_view text, size_t pos) const;
  159. private:
  160. char c_;
  161. };
  162. // ByAnyChar
  163. //
  164. // A delimiter that will match any of the given byte-sized characters within
  165. // its provided string.
  166. //
  167. // Note: this delimiter works with single-byte string data, but does not work
  168. // with variable-width encodings, such as UTF-8.
  169. //
  170. // Example:
  171. //
  172. // using absl::ByAnyChar;
  173. // std::vector<std::string> v = absl::StrSplit("a,b=c", ByAnyChar(",="));
  174. // // v[0] == "a", v[1] == "b", v[2] == "c"
  175. //
  176. // If `ByAnyChar` is given the empty string, it behaves exactly like
  177. // `ByString` and matches each individual character in the input string.
  178. //
  179. class ByAnyChar
  180. {
  181. public:
  182. explicit ByAnyChar(absl::string_view sp);
  183. absl::string_view Find(absl::string_view text, size_t pos) const;
  184. private:
  185. const std::string delimiters_;
  186. };
  187. // ByLength
  188. //
  189. // A delimiter for splitting into equal-length strings. The length argument to
  190. // the constructor must be greater than 0.
  191. //
  192. // Note: this delimiter works with single-byte string data, but does not work
  193. // with variable-width encodings, such as UTF-8.
  194. //
  195. // Example:
  196. //
  197. // using absl::ByLength;
  198. // std::vector<std::string> v = absl::StrSplit("123456789", ByLength(3));
  199. // // v[0] == "123", v[1] == "456", v[2] == "789"
  200. //
  201. // Note that the string does not have to be a multiple of the fixed split
  202. // length. In such a case, the last substring will be shorter.
  203. //
  204. // using absl::ByLength;
  205. // std::vector<std::string> v = absl::StrSplit("12345", ByLength(2));
  206. //
  207. // // v[0] == "12", v[1] == "34", v[2] == "5"
  208. class ByLength
  209. {
  210. public:
  211. explicit ByLength(ptrdiff_t length);
  212. absl::string_view Find(absl::string_view text, size_t pos) const;
  213. private:
  214. const ptrdiff_t length_;
  215. };
  216. namespace strings_internal
  217. {
  218. // A traits-like metafunction for selecting the default Delimiter object type
  219. // for a particular Delimiter type. The base case simply exposes type Delimiter
  220. // itself as the delimiter's Type. However, there are specializations for
  221. // string-like objects that map them to the ByString delimiter object.
  222. // This allows functions like absl::StrSplit() and absl::MaxSplits() to accept
  223. // string-like objects (e.g., ',') as delimiter arguments but they will be
  224. // treated as if a ByString delimiter was given.
  225. template<typename Delimiter>
  226. struct SelectDelimiter
  227. {
  228. using type = Delimiter;
  229. };
  230. template<>
  231. struct SelectDelimiter<char>
  232. {
  233. using type = ByChar;
  234. };
  235. template<>
  236. struct SelectDelimiter<char*>
  237. {
  238. using type = ByString;
  239. };
  240. template<>
  241. struct SelectDelimiter<const char*>
  242. {
  243. using type = ByString;
  244. };
  245. template<>
  246. struct SelectDelimiter<absl::string_view>
  247. {
  248. using type = ByString;
  249. };
  250. template<>
  251. struct SelectDelimiter<std::string>
  252. {
  253. using type = ByString;
  254. };
  255. // Wraps another delimiter and sets a max number of matches for that delimiter.
  256. template<typename Delimiter>
  257. class MaxSplitsImpl
  258. {
  259. public:
  260. MaxSplitsImpl(Delimiter delimiter, int limit) :
  261. delimiter_(delimiter),
  262. limit_(limit),
  263. count_(0)
  264. {
  265. }
  266. absl::string_view Find(absl::string_view text, size_t pos)
  267. {
  268. if (count_++ == limit_)
  269. {
  270. return absl::string_view(text.data() + text.size(),
  271. 0); // No more matches.
  272. }
  273. return delimiter_.Find(text, pos);
  274. }
  275. private:
  276. Delimiter delimiter_;
  277. const int limit_;
  278. int count_;
  279. };
  280. } // namespace strings_internal
  281. // MaxSplits()
  282. //
  283. // A delimiter that limits the number of matches which can occur to the passed
  284. // `limit`. The last element in the returned collection will contain all
  285. // remaining unsplit pieces, which may contain instances of the delimiter.
  286. // The collection will contain at most `limit` + 1 elements.
  287. // Example:
  288. //
  289. // using absl::MaxSplits;
  290. // std::vector<std::string> v = absl::StrSplit("a,b,c", MaxSplits(',', 1));
  291. //
  292. // // v[0] == "a", v[1] == "b,c"
  293. template<typename Delimiter>
  294. inline strings_internal::MaxSplitsImpl<
  295. typename strings_internal::SelectDelimiter<Delimiter>::type>
  296. MaxSplits(Delimiter delimiter, int limit)
  297. {
  298. typedef
  299. typename strings_internal::SelectDelimiter<Delimiter>::type DelimiterType;
  300. return strings_internal::MaxSplitsImpl<DelimiterType>(
  301. DelimiterType(delimiter), limit
  302. );
  303. }
  304. //------------------------------------------------------------------------------
  305. // Predicates
  306. //------------------------------------------------------------------------------
  307. //
  308. // Predicates filter the results of a `StrSplit()` by determining whether or not
  309. // a resultant element is included in the result set. A predicate may be passed
  310. // as an optional third argument to the `StrSplit()` function.
  311. //
  312. // Predicates are unary functions (or functors) that take a single
  313. // `absl::string_view` argument and return a bool indicating whether the
  314. // argument should be included (`true`) or excluded (`false`).
  315. //
  316. // Predicates are useful when filtering out empty substrings. By default, empty
  317. // substrings may be returned by `StrSplit()`, which is similar to the way split
  318. // functions work in other programming languages.
  319. // AllowEmpty()
  320. //
  321. // Always returns `true`, indicating that all strings--including empty
  322. // strings--should be included in the split output. This predicate is not
  323. // strictly needed because this is the default behavior of `StrSplit()`;
  324. // however, it might be useful at some call sites to make the intent explicit.
  325. //
  326. // Example:
  327. //
  328. // std::vector<std::string> v = absl::StrSplit(" a , ,,b,", ',', AllowEmpty());
  329. //
  330. // // v[0] == " a ", v[1] == " ", v[2] == "", v[3] = "b", v[4] == ""
  331. struct AllowEmpty
  332. {
  333. bool operator()(absl::string_view) const
  334. {
  335. return true;
  336. }
  337. };
  338. // SkipEmpty()
  339. //
  340. // Returns `false` if the given `absl::string_view` is empty, indicating that
  341. // `StrSplit()` should omit the empty string.
  342. //
  343. // Example:
  344. //
  345. // std::vector<std::string> v = absl::StrSplit(",a,,b,", ',', SkipEmpty());
  346. //
  347. // // v[0] == "a", v[1] == "b"
  348. //
  349. // Note: `SkipEmpty()` does not consider a string containing only whitespace
  350. // to be empty. To skip such whitespace as well, use the `SkipWhitespace()`
  351. // predicate.
  352. struct SkipEmpty
  353. {
  354. bool operator()(absl::string_view sp) const
  355. {
  356. return !sp.empty();
  357. }
  358. };
  359. // SkipWhitespace()
  360. //
  361. // Returns `false` if the given `absl::string_view` is empty *or* contains only
  362. // whitespace, indicating that `StrSplit()` should omit the string.
  363. //
  364. // Example:
  365. //
  366. // std::vector<std::string> v = absl::StrSplit(" a , ,,b,",
  367. // ',', SkipWhitespace());
  368. // // v[0] == " a ", v[1] == "b"
  369. //
  370. // // SkipEmpty() would return whitespace elements
  371. // std::vector<std::string> v = absl::StrSplit(" a , ,,b,", ',', SkipEmpty());
  372. // // v[0] == " a ", v[1] == " ", v[2] == "b"
  373. struct SkipWhitespace
  374. {
  375. bool operator()(absl::string_view sp) const
  376. {
  377. sp = absl::StripAsciiWhitespace(sp);
  378. return !sp.empty();
  379. }
  380. };
  381. template<typename T>
  382. using EnableSplitIfString =
  383. typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, const std::string>::value, int>::type;
  384. //------------------------------------------------------------------------------
  385. // StrSplit()
  386. //------------------------------------------------------------------------------
  387. // StrSplit()
  388. //
  389. // Splits a given string based on the provided `Delimiter` object, returning the
  390. // elements within the type specified by the caller. Optionally, you may pass a
  391. // `Predicate` to `StrSplit()` indicating whether to include or exclude the
  392. // resulting element within the final result set. (See the overviews for
  393. // Delimiters and Predicates above.)
  394. //
  395. // Example:
  396. //
  397. // std::vector<std::string> v = absl::StrSplit("a,b,c,d", ',');
  398. // // v[0] == "a", v[1] == "b", v[2] == "c", v[3] == "d"
  399. //
  400. // You can also provide an explicit `Delimiter` object:
  401. //
  402. // Example:
  403. //
  404. // using absl::ByAnyChar;
  405. // std::vector<std::string> v = absl::StrSplit("a,b=c", ByAnyChar(",="));
  406. // // v[0] == "a", v[1] == "b", v[2] == "c"
  407. //
  408. // See above for more information on delimiters.
  409. //
  410. // By default, empty strings are included in the result set. You can optionally
  411. // include a third `Predicate` argument to apply a test for whether the
  412. // resultant element should be included in the result set:
  413. //
  414. // Example:
  415. //
  416. // std::vector<std::string> v = absl::StrSplit(" a , ,,b,",
  417. // ',', SkipWhitespace());
  418. // // v[0] == " a ", v[1] == "b"
  419. //
  420. // See above for more information on predicates.
  421. //
  422. //------------------------------------------------------------------------------
  423. // StrSplit() Return Types
  424. //------------------------------------------------------------------------------
  425. //
  426. // The `StrSplit()` function adapts the returned collection to the collection
  427. // specified by the caller (e.g. `std::vector` above). The returned collections
  428. // may contain `std::string`, `absl::string_view` (in which case the original
  429. // string being split must ensure that it outlives the collection), or any
  430. // object that can be explicitly created from an `absl::string_view`. This
  431. // behavior works for:
  432. //
  433. // 1) All standard STL containers including `std::vector`, `std::list`,
  434. // `std::deque`, `std::set`,`std::multiset`, 'std::map`, and `std::multimap`
  435. // 2) `std::pair` (which is not actually a container). See below.
  436. //
  437. // Example:
  438. //
  439. // // The results are returned as `absl::string_view` objects. Note that we
  440. // // have to ensure that the input string outlives any results.
  441. // std::vector<absl::string_view> v = absl::StrSplit("a,b,c", ',');
  442. //
  443. // // Stores results in a std::set<std::string>, which also performs
  444. // // de-duplication and orders the elements in ascending order.
  445. // std::set<std::string> a = absl::StrSplit("b,a,c,a,b", ',');
  446. // // v[0] == "a", v[1] == "b", v[2] = "c"
  447. //
  448. // // `StrSplit()` can be used within a range-based for loop, in which case
  449. // // each element will be of type `absl::string_view`.
  450. // std::vector<std::string> v;
  451. // for (const auto sv : absl::StrSplit("a,b,c", ',')) {
  452. // if (sv != "b") v.emplace_back(sv);
  453. // }
  454. // // v[0] == "a", v[1] == "c"
  455. //
  456. // // Stores results in a map. The map implementation assumes that the input
  457. // // is provided as a series of key/value pairs. For example, the 0th element
  458. // // resulting from the split will be stored as a key to the 1st element. If
  459. // // an odd number of elements are resolved, the last element is paired with
  460. // // a default-constructed value (e.g., empty string).
  461. // std::map<std::string, std::string> m = absl::StrSplit("a,b,c", ',');
  462. // // m["a"] == "b", m["c"] == "" // last component value equals ""
  463. //
  464. // Splitting to `std::pair` is an interesting case because it can hold only two
  465. // elements and is not a collection type. When splitting to a `std::pair` the
  466. // first two split strings become the `std::pair` `.first` and `.second`
  467. // members, respectively. The remaining split substrings are discarded. If there
  468. // are less than two split substrings, the empty string is used for the
  469. // corresponding `std::pair` member.
  470. //
  471. // Example:
  472. //
  473. // // Stores first two split strings as the members in a std::pair.
  474. // std::pair<std::string, std::string> p = absl::StrSplit("a,b,c", ',');
  475. // // p.first == "a", p.second == "b" // "c" is omitted.
  476. //
  477. // The `StrSplit()` function can be used multiple times to perform more
  478. // complicated splitting logic, such as intelligently parsing key-value pairs.
  479. //
  480. // Example:
  481. //
  482. // // The input string "a=b=c,d=e,f=,g" becomes
  483. // // { "a" => "b=c", "d" => "e", "f" => "", "g" => "" }
  484. // std::map<std::string, std::string> m;
  485. // for (absl::string_view sp : absl::StrSplit("a=b=c,d=e,f=,g", ',')) {
  486. // m.insert(absl::StrSplit(sp, absl::MaxSplits('=', 1)));
  487. // }
  488. // EXPECT_EQ("b=c", m.find("a")->second);
  489. // EXPECT_EQ("e", m.find("d")->second);
  490. // EXPECT_EQ("", m.find("f")->second);
  491. // EXPECT_EQ("", m.find("g")->second);
  492. //
  493. // WARNING: Due to a legacy bug that is maintained for backward compatibility,
  494. // splitting the following empty string_views produces different results:
  495. //
  496. // absl::StrSplit(absl::string_view(""), '-'); // {""}
  497. // absl::StrSplit(absl::string_view(), '-'); // {}, but should be {""}
  498. //
  499. // Try not to depend on this distinction because the bug may one day be fixed.
  500. template<typename Delimiter>
  501. strings_internal::Splitter<
  502. typename strings_internal::SelectDelimiter<Delimiter>::type,
  503. AllowEmpty,
  504. absl::string_view>
  505. StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d)
  506. {
  507. using DelimiterType =
  508. typename strings_internal::SelectDelimiter<Delimiter>::type;
  509. return strings_internal::Splitter<DelimiterType, AllowEmpty, absl::string_view>(
  510. text.value(), DelimiterType(d), AllowEmpty()
  511. );
  512. }
  513. template<typename Delimiter, typename StringType, EnableSplitIfString<StringType> = 0>
  514. strings_internal::Splitter<
  515. typename strings_internal::SelectDelimiter<Delimiter>::type,
  516. AllowEmpty,
  517. std::string>
  518. StrSplit(StringType&& text, Delimiter d)
  519. {
  520. using DelimiterType =
  521. typename strings_internal::SelectDelimiter<Delimiter>::type;
  522. return strings_internal::Splitter<DelimiterType, AllowEmpty, std::string>(
  523. std::move(text), DelimiterType(d), AllowEmpty()
  524. );
  525. }
  526. template<typename Delimiter, typename Predicate>
  527. strings_internal::Splitter<
  528. typename strings_internal::SelectDelimiter<Delimiter>::type,
  529. Predicate,
  530. absl::string_view>
  531. StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d, Predicate p)
  532. {
  533. using DelimiterType =
  534. typename strings_internal::SelectDelimiter<Delimiter>::type;
  535. return strings_internal::Splitter<DelimiterType, Predicate, absl::string_view>(
  536. text.value(), DelimiterType(d), std::move(p)
  537. );
  538. }
  539. template<typename Delimiter, typename Predicate, typename StringType, EnableSplitIfString<StringType> = 0>
  540. strings_internal::Splitter<
  541. typename strings_internal::SelectDelimiter<Delimiter>::type,
  542. Predicate,
  543. std::string>
  544. StrSplit(StringType&& text, Delimiter d, Predicate p)
  545. {
  546. using DelimiterType =
  547. typename strings_internal::SelectDelimiter<Delimiter>::type;
  548. return strings_internal::Splitter<DelimiterType, Predicate, std::string>(
  549. std::move(text), DelimiterType(d), std::move(p)
  550. );
  551. }
  552. ABSL_NAMESPACE_END
  553. } // namespace absl
  554. #endif // ABSL_STRINGS_STR_SPLIT_H_