Last active
August 4, 2017 14:20
-
-
Save julianfbeck/5434de3f12fe31bc1a492fff67178eb2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <string.h> | |
| char *extract(char *input, char *pattern); | |
| void extract2(char *input, char **output,char *pattern); | |
| int findPattern(char *input, char *pattern); | |
| typedef struct TestCase { | |
| char *input; | |
| char *expected; | |
| } TestCase; | |
| /** | |
| * Extracts last suffix before the pattern. | |
| * @param input word | |
| * @param pattern to separate the word | |
| * @return suffix | |
| */ | |
| char *extract(char *input, char *pattern) { | |
| //get the len of the input | |
| int len =(int) strlen(input); | |
| /* set pointer to the end, -pattern */ | |
| input+=len-strlen(pattern); | |
| //loop through the word backwards | |
| for (int i =*input; i > 0; --i) { | |
| //check for the pattern | |
| if (findPattern(input, pattern)) { | |
| //if pattern found | |
| //return pointers to end of the Word | |
| //and break | |
| input+=strlen(pattern); | |
| break; | |
| } | |
| input--; | |
| } | |
| return input; | |
| } | |
| /** | |
| * Checks if a pattern exists in the input | |
| * @param input to check | |
| * @param pattern | |
| * @return 0 if not found, 1 if found | |
| */ | |
| int findPattern(char *input, char *pattern) { | |
| //increase patter and input pointer, until | |
| //end of pattern | |
| while (*pattern != '¥0') { | |
| if (*pattern == *input) { | |
| pattern++; | |
| input++; | |
| } else { | |
| return 0; | |
| } | |
| } | |
| return 1; | |
| } | |
| void extract2(char *input, char **output,char *pattern) { | |
| *output=extract(input,pattern); | |
| } | |
| void testsExtract(int no, TestCase *tests,char *pattern) { | |
| for (int i = 0; i < no; ++i) { | |
| printf("Test %i: Testing: '%s'¥n", i, tests[i].input); | |
| printf("Expecting: '%s'¥n", tests[i].expected); | |
| char *output; | |
| extract2(tests[i].input,&output,pattern); | |
| char *input = extract(tests[i].input, pattern); | |
| printf("Result Extract1: '%s'¥n", input); | |
| printf("Result Extract2: '%s'¥n", output); | |
| if (!strcmp(input, tests[i].expected)) { | |
| printf("OK¥n"); | |
| printf("¥n"); | |
| } else { | |
| printf("FAIL ¥n"); | |
| printf("¥n"); | |
| } | |
| } | |
| } | |
| int main(void) { | |
| const int no = 7; | |
| TestCase tests[no] = { | |
| {"::Ha::ll:::o", "o"}, | |
| {"1241::12::231", "231"}, | |
| {"47::11", "11"}, | |
| {"::47", "4s7"}, | |
| {":hallo::", ""}, | |
| {":hallo", ""}, | |
| {"", ""}, | |
| }; | |
| testsExtract(no, tests,"::"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment