1 // Copyright 2015 The Weave Authors. All rights reserved.
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>
JoinRange(const std::string & delimiter,InputIterator first,InputIterator last)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>
Join(const std::string & delimiter,const Container & strings)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
Join(const std::string & delimiter,const std::string & str1,const std::string & str2)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_
62