blob: 20da144a40910997dc634d12e29e36c709207467 [file] [log] [blame]
Dan Albert0f1e5442015-03-13 22:57:40 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
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 * http://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#ifndef BASE_STRINGS_H
18#define BASE_STRINGS_H
19
Dan Alberte0da8a12015-05-21 18:37:36 -070020#include <sstream>
Dan Albert0f1e5442015-03-13 22:57:40 -070021#include <string>
22#include <vector>
23
24namespace android {
25namespace base {
26
Dan Albert47328c92015-03-19 13:24:26 -070027// Splits a string into a vector of strings.
28//
Elliott Hughes1daf86a2015-04-17 17:08:16 -070029// The string is split at each occurrence of a character in delimiters.
Dan Albert47328c92015-03-19 13:24:26 -070030//
Dan Albert47328c92015-03-19 13:24:26 -070031// The empty string is not a valid delimiter list.
32std::vector<std::string> Split(const std::string& s,
33 const std::string& delimiters);
Dan Albert0f1e5442015-03-13 22:57:40 -070034
35// Trims whitespace off both ends of the given string.
36std::string Trim(const std::string& s);
37
Dan Alberte0da8a12015-05-21 18:37:36 -070038// Joins a container of things into a single string, using the given separator.
Casey Dahlin5345f1d2015-10-30 18:54:38 -070039template <typename ContainerT, typename SeparatorT>
40std::string Join(const ContainerT& things, SeparatorT separator) {
Dan Alberte0da8a12015-05-21 18:37:36 -070041 if (things.empty()) {
42 return "";
43 }
44
45 std::ostringstream result;
46 result << *things.begin();
47 for (auto it = std::next(things.begin()); it != things.end(); ++it) {
48 result << separator << *it;
49 }
50 return result.str();
51}
52
53// We instantiate the common cases in strings.cpp.
54extern template std::string Join(const std::vector<std::string>&, char);
55extern template std::string Join(const std::vector<const char*>&, char);
Casey Dahlin5345f1d2015-10-30 18:54:38 -070056extern template std::string Join(const std::vector<std::string>&, const std::string&);
57extern template std::string Join(const std::vector<const char*>&, const std::string&);
Dan Albert0f1e5442015-03-13 22:57:40 -070058
59// Tests whether 's' starts with 'prefix'.
60bool StartsWith(const std::string& s, const char* prefix);
61
62// Tests whether 's' ends with 'suffix'.
63bool EndsWith(const std::string& s, const char* suffix);
64
65} // namespace base
66} // namespace android
67
68#endif // BASE_STRINGS_H