forked from hughperkins/EasyCL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasycl_stringhelper.cpp
97 lines (88 loc) · 2.98 KB
/
easycl_stringhelper.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include <string>
#include <vector>
#include <sstream>
using namespace std;
#include "easycl_stringhelper.h"
namespace easycl {
vector<string> split(const string &str, const string &separator) {
vector<string> splitstring;
int start = 0;
int npos = (int)str.find(separator);
while (npos != (int)str.npos) {
splitstring.push_back(str.substr(start, npos-start));
start = npos + (int)separator.length();
npos = (int)str.find(separator, start);
}
splitstring.push_back(str.substr(start) );
return splitstring;
}
string trim(const string &target) {
int origlen = (int)target.size();
int startpos = -1;
for(int i = 0; i < origlen; i++) {
if(target[i] != ' ' && target[i] != '\r' && target[i] != '\n') {
startpos = i;
break;
}
}
int endpos = -1;
for(int i = origlen - 1; i >= 0; i--) {
if(target[i] != ' ' && target[i] != '\r' && target[i] != '\n') {
endpos = i;
break;
}
}
if(startpos == -1 || endpos == -1) {
return "";
}
return target.substr(startpos, endpos-startpos + 1);
}
string replace(string targetString, string oldValue, string newValue) {
size_t pos = targetString.find(oldValue);
if(pos == string::npos) {
return targetString;
}
return targetString.replace(pos, oldValue.length(), newValue);
}
string replaceGlobal(string targetString, string oldValue, string newValue) {
int pos = 0;
string resultString = "";
size_t targetPos = targetString.find(oldValue, pos);
while(targetPos != string::npos) {
string preOld = targetString.substr(pos, targetPos - pos);
resultString += preOld + newValue;
pos = targetPos + oldValue.length();
targetPos = targetString.find(oldValue, pos);
}
resultString += targetString.substr(pos);
return resultString;
}
std::string toLower(std::string in) {
int len = static_cast<int>(in.size());
char *buffer = new char[len + 1];
for(int i = 0; i < len; i++) {
char thischar = in[i];
thischar = tolower(thischar);
buffer[i] = thischar;
}
buffer[len] = 0;
std::string result = std::string(buffer);
delete[] buffer;
return result;
}
void strcpy_safe(char *destination, char const*source, int maxLength) {
int i = 0;
for(i = 0; i < maxLength; i++) {
destination[i] = source[i];
if(source[i] == 0) {
break;
}
}
destination[i] = 0;
}
}