-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringUtils.cpp
More file actions
70 lines (60 loc) · 1.74 KB
/
StringUtils.cpp
File metadata and controls
70 lines (60 loc) · 1.74 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
64
65
66
67
68
69
70
//
// Created by root on 11/6/17.
//
#include "StringUtils.h"
// trim from start (in place)
void StringUtils::ltrim(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)
void StringUtils::rtrim(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)
void StringUtils::trim(std::string &s) {
ltrim(s);
rtrim(s);
}
// trim from start (copying)
std::string StringUtils::ltrim_copy(std::string s) {
ltrim(s);
return s;
}
// trim from end (copying)
std::string StringUtils::rtrim_copy(std::string s) {
rtrim(s);
return s;
}
// trim from both ends (copying)
std::string StringUtils::trim_copy(std::string s) {
trim(s);
return s;
}
std::string StringUtils::replace(std::string subject, const std::string& search, const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
std::string StringUtils::replaceFirst(std::string subject, const std::string& search, const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
break;
}
return subject;
}
int StringUtils::indexOf(const std::string &text, const std::string &target) {
int index = -1;
std::size_t found = text.find(target);
if (found!=std::string::npos)
index = static_cast<int>(found);
return index;
}