1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
#include "str.hh"
#include <cstddef>
#include <string_view>
#include <vector>
namespace str {
namespace {
[[nodiscard]]
inline bool is_space(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
} // namespace
void split(std::string_view str, std::vector<std::string_view>& out,
char separator, bool keep_empty) {
out.clear();
size_t offset = 0;
while (true) {
auto next = str.find(separator, offset);
if (next == std::string_view::npos) {
if (keep_empty || offset < str.size())
out.push_back(str.substr(offset));
break;
}
if (keep_empty || offset < next)
out.push_back(str.substr(offset, next - offset));
offset = next + 1;
}
}
std::vector<std::string_view> split(std::string_view str, char separator,
bool keep_empty) {
std::vector<std::string_view> vec;
split(str, vec, separator, keep_empty);
return vec;
}
void split(std::string_view str, std::vector<std::string_view>& out,
std::string_view separator, bool keep_empty) {
out.clear();
size_t offset = 0;
while (true) {
auto next = str.find(separator, offset);
if (next == std::string_view::npos) {
if (keep_empty || offset < str.size())
out.push_back(str.substr(offset));
break;
}
if (keep_empty || offset < next)
out.push_back(str.substr(offset, next - offset));
offset = next + separator.size();
}
}
std::vector<std::string_view> split(std::string_view str,
std::string_view separator,
bool keep_empty) {
std::vector<std::string_view> vec;
split(str, vec, separator, keep_empty);
return vec;
}
std::string_view trim(std::string_view str) {
size_t s = 0;
size_t e = str.size();
while (s < e && is_space(str[s]))
++s;
while (e > s && is_space(str[e - 1]))
--e;
return str.substr(s, e - s);
}
std::string_view ltrim(std::string_view str) {
size_t s = 0;
size_t const e = str.size();
while (s < e && is_space(str[s]))
++s;
return str.substr(s, e - s);
}
std::string_view rtrim(std::string_view str) {
size_t e = str.size();
while (e > 0 && is_space(str[e - 1]))
--e;
return str.substr(0, e);
}
} // namespace str
|