blob: e349d9df5111392bf3abbb0f0b7171b237f44622 [file] [log] [blame]
Vitaly Buka4615e0d2015-10-14 15:35:12 -07001// Copyright 2015 The Weave Authors. All rights reserved.
Vitaly Buka24d6fd52015-08-13 23:22:48 -07002// 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
12namespace 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.
19std::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.
26std::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|.
31template <class InputIterator>
32std::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
46template <class Container>
47std::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
53inline 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_