Vitaly Buka | 4615e0d | 2015-10-14 15:35:12 -0700 | [diff] [blame] | 1 | // Copyright 2015 The Weave Authors. All rights reserved. |
Vitaly Buka | 24d6fd5 | 2015-08-13 23:22:48 -0700 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef LIBWEAVE_SRC_STRING_UTILS_H_ |
| 6 | #define LIBWEAVE_SRC_STRING_UTILS_H_ |
| 7 | |
| 8 | #include <string> |
| 9 | #include <utility> |
| 10 | #include <vector> |
| 11 | |
| 12 | namespace weave { |
| 13 | |
| 14 | // Treats the string as a delimited list of substrings and returns the array |
| 15 | // of original elements of the list. |
| 16 | // |trim_whitespaces| causes each element to have all whitespaces trimmed off. |
| 17 | // |purge_empty_strings| specifies whether empty elements from the original |
| 18 | // string should be omitted. |
| 19 | std::vector<std::string> Split(const std::string& str, |
| 20 | const std::string& delimiter, |
| 21 | bool trim_whitespaces, |
| 22 | bool purge_empty_strings); |
| 23 | |
| 24 | // Splits the string into two pieces at the first position of the specified |
| 25 | // delimiter. |
| 26 | std::pair<std::string, std::string> SplitAtFirst(const std::string& str, |
| 27 | const std::string& delimiter, |
| 28 | bool trim_whitespaces); |
| 29 | |
| 30 | // Joins strings into a single string separated by |delimiter|. |
| 31 | template <class InputIterator> |
| 32 | std::string JoinRange(const std::string& delimiter, |
| 33 | InputIterator first, |
| 34 | InputIterator last) { |
| 35 | std::string result; |
| 36 | if (first == last) |
| 37 | return result; |
| 38 | result = *first; |
| 39 | for (++first; first != last; ++first) { |
| 40 | result += delimiter; |
| 41 | result += *first; |
| 42 | } |
| 43 | return result; |
| 44 | } |
| 45 | |
| 46 | template <class Container> |
| 47 | std::string Join(const std::string& delimiter, const Container& strings) { |
| 48 | using std::begin; |
| 49 | using std::end; |
| 50 | return JoinRange(delimiter, begin(strings), end(strings)); |
| 51 | } |
| 52 | |
| 53 | inline std::string Join(const std::string& delimiter, |
| 54 | const std::string& str1, |
| 55 | const std::string& str2) { |
| 56 | return str1 + delimiter + str2; |
| 57 | } |
| 58 | |
| 59 | } // namespace weave |
| 60 | |
| 61 | #endif // LIBWEAVE_SRC_STRING_UTILS_H_ |