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 #pragma once
18
19 #include <sstream>
20 #include <string>
21 #include <vector>
22
23 namespace android {
24 namespace base {
25
26 // Splits a string into a vector of strings.
27 //
28 // The string is split at each occurrence of a character in delimiters.
29 //
30 // The empty string is not a valid delimiter list.
31 std::vector<std::string> Split(const std::string& s,
32 const std::string& delimiters);
33
34 // Trims whitespace off both ends of the given string.
35 std::string Trim(const std::string& s);
36
37 // Joins a container of things into a single string, using the given separator.
38 template <typename ContainerT, typename SeparatorT>
Join(const ContainerT & things,SeparatorT separator)39 std::string Join(const ContainerT& things, SeparatorT separator) {
40 if (things.empty()) {
41 return "";
42 }
43
44 std::ostringstream result;
45 result << *things.begin();
46 for (auto it = std::next(things.begin()); it != things.end(); ++it) {
47 result << separator << *it;
48 }
49 return result.str();
50 }
51
52 // We instantiate the common cases in strings.cpp.
53 extern template std::string Join(const std::vector<std::string>&, char);
54 extern template std::string Join(const std::vector<const char*>&, char);
55 extern template std::string Join(const std::vector<std::string>&, const std::string&);
56 extern template std::string Join(const std::vector<const char*>&, const std::string&);
57
58 // Tests whether 's' starts with 'prefix'.
59 bool StartsWith(std::string_view s, std::string_view prefix);
60 bool StartsWith(std::string_view s, char prefix);
61 bool StartsWithIgnoreCase(std::string_view s, std::string_view prefix);
62
63 // Tests whether 's' ends with 'suffix'.
64 bool EndsWith(std::string_view s, std::string_view suffix);
65 bool EndsWith(std::string_view s, char suffix);
66 bool EndsWithIgnoreCase(std::string_view s, std::string_view suffix);
67
68 // Tests whether 'lhs' equals 'rhs', ignoring case.
69 bool EqualsIgnoreCase(std::string_view lhs, std::string_view rhs);
70
71 } // namespace base
72 } // namespace android
73