-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.cpp
82 lines (70 loc) · 2.09 KB
/
utils.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
#include "utils.h"
#include <algorithm>
#include <regex>
bool replace(std::string &str, const std::string &from, const std::string &to) {
size_t start_pos = str.find(from);
if (start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
bool replace(std::string &str, const char *from, const char *to) {
size_t start_pos = str.find(from);
if (start_pos == std::string::npos)
return false;
str.replace(start_pos, strlen(from), to);
return true;
}
bool file_exists(const std::string &name) {
std::ifstream f(name.c_str());
return f.good();
}
bool file_exists(const char *name) {
std::ifstream f(name);
return f.good();
}
void string_toupper(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}
/**
* @brief Case Insensitive std::string compare
*
* @param a
* @param b
* @return true
* @return false
*/
bool iequals(const std::string &a, const std::string &b) {
unsigned int sz = a.size();
if (b.size() != sz)
return false;
for (unsigned int i = 0; i < sz; ++i)
if (std::tolower(a[i]) != std::tolower(b[i]))
return false;
return true;
}
std::vector<std::pair<int, int>> find_words(const std::string &text) {
std::vector<std::pair<int, int>> words;
// this is expensive to construct, so only construct it once.
static std::regex word("([a-zA-Z]+)");
for (auto it = std::sregex_iterator(text.begin(), text.end(), word);
it != std::sregex_iterator(); ++it) {
words.push_back(std::make_pair(it->position(), it->length()));
}
return words;
}
// From: https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string
std::vector<std::string> split(const std::string &text, char sep) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
if (end != start) {
tokens.push_back(text.substr(start, end - start));
}
start = end + 1;
}
if (end != start) {
tokens.push_back(text.substr(start));
}
return tokens;
}