-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrimming_whitespace.cpp
More file actions
44 lines (34 loc) · 984 Bytes
/
Copy pathtrimming_whitespace.cpp
File metadata and controls
44 lines (34 loc) · 984 Bytes
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
/*
String Trimming (the functional way)
Strip whitespace from the start and end of a string.
(see pg. 31 of Functional Programming in C++, by Ivan Čukić)
*/
#include <iostream>
#include <string>
#include <algorithm> // std::find_if(), std::move()
using std::cout;
using std::string;
bool is_not_space(char c);
string trim_left(string s);
string trim_right(string s);
string trim(string s);
int main()
{
string input = " Subterranian Homesick Blues ";
cout << "|" << trim(input) << "|" << '\n';
}
bool is_not_space(char c) {
return (c != ' ') ? true : false;
}
string trim_left(string s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), is_not_space));
return s;
}
string trim_right(string s) {
s.erase(std::find_if(s.rbegin(), s.rend(), is_not_space).base(), s.end());
return s;
}
/* Composing the two functions above for the full trim function */
string trim(string s) {
return trim_left(trim_right(std::move(s)));
}