-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utility.hh
106 lines (94 loc) · 2.55 KB
/
Utility.hh
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
97
98
99
100
101
102
103
104
105
106
/*
@file Utility.hh
@author Ayoub Ouarrak, ouarrakayoub@gmail.com
@version 1.0
*/
#ifndef GUARD_UTILITY_REGEX
#define GUARD_UTILITY_REGEX
#include <iterator>
#include <iostream>
#include <cstdlib>
#include <utility>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
namespace utility {
/**
Convert to string
@param n type to convert to string
*/
template<typename T> std::string to_string(const T& n) {
std::ostringstream stm;
stm << n;
return stm.str();
}
/**
Transform string 2-4 to pair <2, 4>
@param s string to transform
@return pair of int
*/
std::pair<int, int> interval(std::string s) {
// tokenize the string
int i = s.length() - 1;
unsigned power = 0;
int toInt = 0;
int fromInt = 0;
while(s.at(i) != '-') {
toInt += (s.at(i--) - 48) * pow(10, power++);
}
power = 0;
--i;
while(i != -1) {
fromInt += (s.at(i--) - 48) * pow(10, power++);
}
return std::make_pair(fromInt, toInt);
}
/**
a-d -> [a, b, c, d] | A-Z -> [A, B, C, ..., Z]
@param s string to parse
@return vector of char
*/
std::vector<char> regexChar(std::string s) {
std::vector<char> tmp;
int head = s.at(0);
int tail = s.at(2);
while(head != tail) {
tmp.push_back(head++);
}
tmp.push_back(head);
return tmp;
}
/**
1-4 -> [1,2,3,4] 34-101 -> [34,35,36,...,100,101]
@param s string to parse
@return vector of int
*/
std::vector<int> regexInt(std::string s) {
// generate the number from (fromInt) to (toInt)
std::vector<int> tmp;
std::pair<int , int> intval(interval(s));
for(int i = intval.first; i <= intval.second; ++i) {
tmp.push_back(i);
}
return tmp;
}
/**
Check of s is a valid interval
@param s interval to check
@return bool
*/
bool checkIfInterval(std::string s) {
std::pair<int, int> intval(interval(s));
std::string fromInt = to_string(intval.first);
std::string toInt = to_string(intval.second);
std::string::const_iterator fromIt = fromInt.begin();
std::string::const_iterator toIt = toInt.begin();
while(fromIt != fromInt.end() && std::isdigit(*fromIt)) ++fromIt;
while(toIt != toInt.end() && std::isdigit(*toIt)) ++toIt;
return (!fromInt.empty() && fromIt == fromInt.end()) &&
(!toInt.empty() && toIt == toInt.end());
}
/** namespace utility */
}
#endif