-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstring_trim(strip).cpp
64 lines (54 loc) · 1.66 KB
/
string_trim(strip).cpp
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
#include <algorithm>
#include <iostream>
//https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
// trim from start (in place)
static inline void trim_left(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void trim_right(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim_all(std::string &s) {
trim_left(s);
trim_right(s);
}
// trim from start (copying)
static inline std::string trim_left_copy(std::string s) {
trim_left(s);
return s;
}
// trim from end (copying)
static inline std::string trim_right_copy(std::string s) {
trim_right(s);
return s;
}
// trim from both ends (copying)
static inline std::string trim_all_copy(std::string s) {
trim_all(s);
return s;
}
// g++ string_trim\(strip\).cpp -std=c++11
int main(){
std::string str = " hello world! ";
std::cout << "trim left: '" << trim_left_copy(str) << "'" << std::endl;
std::cout << "trim right: '" << trim_right_copy(str) << "'" << std::endl;
std::cout << "trim all: '" << trim_all_copy(str) << "'" << std::endl;
trim_left(str);
std::cout << "trim left(in-place): '" << str << "'" << std::endl;
trim_right(str);
std::cout << "trim right(in-place): '" << str << "'" << std::endl;
return 0;
}
/*
trim left: 'hello world! '
trim right: ' hello world!'
trim all: 'hello world!'
trim left(in-place): 'hello world! '
trim right(in-place): 'hello world!'
*/