-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexer.cpp
More file actions
131 lines (122 loc) · 3.25 KB
/
Copy pathLexer.cpp
File metadata and controls
131 lines (122 loc) · 3.25 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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//
// Created by roy on 12/17/18.
//
#include "Lexer.h"
#include <string>
using namespace std;
/**
* This function receives a string and iterates through it, inserting
* expressions represented as strings to a string array.
* @param str given string.
* @return array of strings representing expressions.
*/
vector<string> Lexer::lexer(string str) {
vector<string> stringArray;
string currentStr;
int i = 0;
// iterate each char in string.
while (i < str.length()) {
// if whitespace or ',' - starts a new string.
if (isspace(str.at(i)) || str.at(i) == ',') {
if (!currentStr.empty()) {
stringArray.push_back(currentStr);
}
currentStr = "";
i++;
continue;
}
// if the char is a digit - while there are more digits following it - add them to string.
else if (isdigit(str.at(i))) {
while (i < str.length() && (isdigit(str.at(i)) || str.at(i) == '.')) {
currentStr += str.at(i);
i++;
}
stringArray.push_back(currentStr);
currentStr = "";
continue;
}
// if the char is " (double quotes = beginning of a string) - add chars until next ".
else if (str.at(i) == '"') {
currentStr += str.at(i);
i++;
while (i < str.length() && str.at(i) != '"') {
currentStr += str.at(i);
i++;
}
currentStr += str.at(i);
stringArray.push_back(currentStr);
i++;
currentStr = "";
continue;
}
// if the char is of the alphabet, add it and continue.
else if (isalpha(str.at(i))) {
currentStr += str.at(i);
i++;
continue;
}
// if the char is an operator, add it, reset the string and continue.
else if (this->isOperator(str.at(i))) {
currentStr += str.at(i);
stringArray.push_back(currentStr);
i++;
currentStr = "";
continue;
}
// if not valid.
else
{
i++;
}
}
if (!currentStr.empty()) {
stringArray.push_back(currentStr);
}
return stringArray;
}
/**
* This method checks if a char is a valid operator.
* @param c given char.
* @return boolean - true if c is an operator, else false.
*/
bool Lexer::isOperator(char c) {
bool isOp;
switch (c) {
case '+' :
isOp = true;
break;
case '-' :
isOp = true;
break;
case '*' :
isOp = true;
break;
case '/' :
isOp = true;
break;
case '=' :
isOp = false;
break;
case '(' :
isOp = true;
break;
case ')' :
isOp = true;
break;
case '{' :
isOp = true;
break;
case '}' :
isOp = true;
break;
case '>' :
isOp = true;
break;
case '<' :
isOp = true;
break;
default:
isOp = false;
}
return isOp;
}