libcosmos
Linux C++ System Programming Library
All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
string.cxx
1// cosmos
2#include <cosmos/string.hxx>
3
4// C++
5#include <algorithm>
6#include <cctype>
7#include <ostream>
8
9namespace cosmos {
10
11std::string to_lower(const std::string_view s) {
12 std::string ret;
13 ret.resize(s.size());
14 // put it all to lower case
15 std::transform(
16 s.begin(), s.end(),
17 ret.begin(),
18 ::tolower
19 );
20
21 return ret;
22}
23
24std::string to_upper(const std::string_view s) {
25 std::string ret;
26 ret.resize(s.size());
27 // put it all to lower case
28 std::transform(
29 s.begin(), s.end(),
30 ret.begin(),
31 ::toupper
32 );
33
34 return ret;
35}
36
37std::wstring to_lower(const std::wstring_view s) {
38 std::wstring ret;
39 ret.resize(s.size());
40 // put it all to lower case
41 std::transform(
42 s.begin(), s.end(),
43 ret.begin(),
44 std::towlower
45 );
46
47 return ret;
48}
49
50std::wstring to_upper(const std::wstring_view s) {
51 std::wstring ret;
52 ret.resize(s.size());
53 // put it all to lower case
54 std::transform(
55 s.begin(), s.end(),
56 ret.begin(),
57 std::towupper
58 );
59
60 return ret;
61}
62
63void strip(std::string &s) {
64 while (!s.empty() && std::isspace(s[0]))
65 s.erase(s.begin());
66
67 while (!s.empty() && std::isspace(s.back()))
68 s.pop_back();
69}
70
71void strip(std::wstring &s) {
72 while (!s.empty() && std::iswspace(s[0]))
73 s.erase(s.begin());
74
75 while (!s.empty() && std::iswspace(s.back()))
76 s.pop_back();
77}
78
79template <typename CHAR>
80std::vector<std::basic_string<CHAR>> split(
81 const std::basic_string_view<CHAR> str,
82 const std::basic_string_view<CHAR> sep,
83 const SplitFlags flags) {
84
85 using String = std::basic_string<CHAR>;
86 std::vector<String> parts;
87
88 // index of current start of token
89 size_t pos1;
90 // index of current end of token
91 size_t pos2 = 0;
92
93 while(true) {
94 String token;
95
96 pos1 = pos2;
97
98 if (!flags[SplitFlag::KEEP_EMPTY]) {
99 while (str.substr(pos1, sep.size()) == sep)
100 pos1 += sep.size();
101 }
102
103 pos2 = str.find(sep, pos1);
104
105 auto token_len = pos2 - pos1;
106
107 if (token_len) {
108 token = str.substr(pos1, token_len);
109
110 if (flags[SplitFlag::STRIP_PARTS]) {
111 strip(token);
112 }
113 }
114
115 if (!token.empty() || flags[SplitFlag::KEEP_EMPTY]) {
116 parts.push_back(token);
117 }
118
119 if (pos2 == str.npos)
120 break;
121
122 pos2 += sep.size();
123 }
124
125 return parts;
126}
127
128/* explicit instantiations for outlined template functions */
129
130template COSMOS_API std::vector<std::basic_string<char>> split(
131 const std::basic_string_view<char> str,
132 const std::basic_string_view<char> sep,
133 const SplitFlags flags);
134
135} // end ns
A typesafe bit mask representation using class enums.
Definition BitMask.hxx:19