-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ24.cpp
More file actions
63 lines (49 loc) · 1.6 KB
/
Q24.cpp
File metadata and controls
63 lines (49 loc) · 1.6 KB
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
// 24. Write a program to remove whitespace from both ends of a string. Example: Input: " hello ", Output: "hello".
#include <iostream>
#include <cctype>
using namespace std;
string trimManual(string str) {
int start = 0, end = str.length() - 1;
while (start <= end && isspace(str[start])) {
start++;
}
while (end >= start && isspace(str[end])) {
end--;
}
return str.substr(start, end - start + 1);
}
int main() {
string input = " hello ";
cout << "Trimmed String (Manual): \"" << trimManual(input) << "\"" << endl;
return 0;
}
//
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
string trimUsingErase(string str) {
str.erase(str.begin(), find_if(str.begin(), str.end(), [](unsigned char ch) { return !isspace(ch); }));
str.erase(find_if(str.rbegin(), str.rend(), [](unsigned char ch) { return !isspace(ch); }).base(), str.end());
return str;
}
int main() {
string input = " hello ";
cout << "Trimmed String (Using erase()): \"" << trimUsingErase(input) << "\"" << endl;
return 0;
}
//
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
string trimUsingSTL(string str) {
auto start = find_if_not(str.begin(), str.end(), [](unsigned char ch) { return isspace(ch); });
auto end = find_if_not(str.rbegin(), str.rend(), [](unsigned char ch) { return isspace(ch); }).base();
return (start < end ? string(start, end) : "");
}
int main() {
string input = " hello ";
cout << "Trimmed String (Using STL): \"" << trimUsingSTL(input) << "\"" << endl;
return 0;
}