-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrim.h
61 lines (52 loc) · 1.52 KB
/
trim.h
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
#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>
#include <cwctype>
namespace {
namespace detail {
struct is_space_or_null {
bool operator ()(char ch) const {
return ch == '\0' || !!std::isspace(static_cast<unsigned char>(ch));
}
bool operator ()(wchar_t ch) const {
return ch == L'\0' || !!std::iswspace(ch);
}
};
}
template<typename StringT, typename UnaryPredicate = detail::is_space_or_null>
void ltrim_inplace(StringT& s, UnaryPredicate pred = {})
{
s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), pred));
}
template<typename StringT, typename UnaryPredicate = detail::is_space_or_null>
void rtrim_inplace(StringT& s, UnaryPredicate pred)
{
s.erase(std::find_if_not(s.rbegin(), s.rend(), pred).base(), s.end());
}
template<typename StringT, typename UnaryPredicate = detail::is_space_or_null>
void trim_inplace(StringT& s, UnaryPredicate pred = {})
{
ltrim_inplace(s, pred);
rtrim_inplace(s, pred);
}
template<typename StringT, typename UnaryPredicate = detail::is_space_or_null>
StringT ltrim(StringT s, UnaryPredicate pred = {})
{
ltrim_inplace(s, pred);
return s;
}
template<typename StringT, typename UnaryPredicate = detail::is_space_or_null>
StringT rtrim(StringT s, UnaryPredicate pred = {})
{
rtrim_inplace(s, pred);
return s;
}
template<typename StringT, typename UnaryPredicate = detail::is_space_or_null>
StringT trim(StringT s, UnaryPredicate pred = {})
{
ltrim_inplace(s, pred);
rtrim_inplace(s, pred);
return s;
}
}