Created
September 29, 2017 14:57
-
-
Save ConorOBrien-Foxx/3478d5da63a386443320b483a54f3627 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdarg.h> | |
typedef struct operator { | |
char* name; | |
int prec; | |
} operator; | |
int needle(char* str, char* search) { | |
int size = 0; | |
while(search[size]) { | |
if(!str[size] || search[size] != str[size]) | |
return -1; | |
size++; | |
} | |
return size; | |
} | |
// needle_any("search", 3, "sea", "urchin", "idk"); | |
int needle_any(char* str, int count, ...) { | |
va_list args; | |
va_start(args, count); | |
int res; | |
while(count --> 0) { | |
char* search = va_arg(args, char*); | |
res = needle(str, search); | |
if(res != -1) | |
return res; | |
} | |
va_end(args); | |
return -1; | |
} | |
// converts string like (T && F) || F to single characters: (T&F)|F | |
#define CASE(count,signature,...)\ | |
if((tok_length = needle_any(str + pos, count, __VA_ARGS__)) != -1) {\ | |
res[*outsize] = signature;\ | |
(*outsize)++;\ | |
pos += tok_length;\ | |
} | |
char* tokenize(char* str, size_t size, size_t* outsize) { | |
char* res = malloc((size + 1) * sizeof(char)); | |
size_t pos = 0; | |
*outsize = 0; | |
//printf("%i\n", *outsize); | |
while(pos < size) { | |
//printf("str[%i] = %c; outsize = %i\n", pos, str[pos], *outsize); | |
int tok_length; | |
CASE(2, 'T', "true", "T") | |
else CASE(2, 'F', "false", "F") | |
else CASE(3, '|', "or", "||", "|") | |
else CASE(3, '&', "and", "&&". "&") | |
else CASE(3, '!', "not", "!", "~") | |
else CASE(1, '(', "(") | |
else CASE(1, ')', ")") | |
else | |
pos++; | |
} | |
//printf("%i\n", *outsize); | |
res[*outsize] = '\0'; | |
return res; | |
} | |
int main() { | |
char* str = "(true or false)or T"; | |
size_t size = strlen(str), outsize; | |
char* res = tokenize(str, size, &outsize); | |
puts(res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment