1 /*
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 ANDROID_BASE_STRINGS_H
18 #define ANDROID_BASE_STRINGS_H
19
20 #include <sstream>
21 #include <string>
22 #include <vector>
23
24 namespace android {
25 namespace base {
26
27 // Splits a string into a vector of strings.
28 //
29 // The string is split at each occurrence of a character in delimiters.
30 //
31 // The empty string is not a valid delimiter list.
32 std::vector<std::string> Split(const std::string& s,
33 const std::string& delimiters);
34
35 // Trims whitespace off both ends of the given string.
36 std::string Trim(const std::string& s);
37
38 // Joins a container of things into a single string, using the given separator.
39 template <typename ContainerT, typename SeparatorT>
Join(const ContainerT & things,SeparatorT separator)40 std::string Join(const ContainerT& things, SeparatorT separator) {
41 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.
54 extern template std::string Join(const std::vector<std::string>&, char);
55 extern template std::string Join(const std::vector<const char*>&, char);
56 extern template std::string Join(const std::vector<std::string>&, const std::string&);
57 extern template std::string Join(const std::vector<const char*>&, const std::string&);
58
59 // Tests whether 's' starts with 'prefix'.
60 bool StartsWith(const std::string& s, const char* prefix);
61 bool StartsWithIgnoreCase(const std::string& s, const char* prefix);
62
63 // Tests whether 's' ends with 'suffix'.
64 bool EndsWith(const std::string& s, const char* suffix);
65 bool EndsWithIgnoreCase(const std::string& s, const char* suffix);
66
67 // Tests whether 'lhs' equals 'rhs', ignoring case.
68 bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs);
69
70 } // namespace base
71 } // namespace android
72
73 #endif // ANDROID_BASE_STRINGS_H
74