btllib

util.hpp
1 #ifndef BTLLIB_UTIL_HPP
2 #define BTLLIB_UTIL_HPP
3
4 #include <algorithm>
5 #include <string>
6 #include <vector>
7
8 namespace btllib {
9
10 inline std::vector<std::string>
11 split(const std::string& s, const std::string& delim);
12 inline void
13 ltrim(std::string& s);
14 inline void
15 rtrim(std::string& s);
16 inline void
17 trim(std::string& s);
18 inline bool
19 starts_with(std::string s, std::string prefix);
20 inline bool
21 ends_with(std::string s, std::string suffix);
22
23 inline std::vector<std::string>
24 split(const std::string& s, const std::string& delim)
25 {
26 std::vector<std::string> tokens;
27 size_t pos1 = 0, pos2 = 0;
28 while ((pos2 = s.find(delim, pos2)) != std::string::npos) {
29 tokens.push_back(s.substr(pos1, pos2 - pos1));
30 pos2 += delim.size();
31 pos1 = pos2;
32 }
33 tokens.push_back(s.substr(pos1));
34 return tokens;
35 }
36
37 inline void
38 ltrim(std::string& s)
39 {
40 s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
41 return !bool(std::isspace(ch));
42 }));
43 }
44
45 inline void
46 rtrim(std::string& s)
47 {
48 s.erase(std::find_if(s.rbegin(),
49 s.rend(),
50 [](int ch) { return !bool(std::isspace(ch)); })
51 .base(),
52 s.end());
53 }
54
55 inline void
56 trim(std::string& s)
57 {
58 ltrim(s);
59 rtrim(s);
60 }
61
62 inline bool
63 starts_with(std::string s, std::string prefix)
64 {
65 std::transform(s.begin(), s.end(), s.begin(), ::tolower);
66 std::transform(prefix.begin(), prefix.end(), prefix.begin(), ::tolower);
67 return s.find(prefix) == 0;
68 };
69
70 inline bool
71 ends_with(std::string s, std::string suffix)
72 {
73 std::transform(s.begin(), s.end(), s.begin(), ::tolower);
74 std::transform(suffix.begin(), suffix.end(), suffix.begin(), ::tolower);
75 auto pos = s.rfind(suffix);
76 return (pos != std::string::npos) && (pos == s.size() - suffix.size());
77 };
78
79 } // namespace btllib
80
81 #endif