Created
October 29, 2014 08:35
-
-
Save DivinityArcane/c2e8966cb529156a581a to your computer and use it in GitHub Desktop.
because strtok was being evil
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 <string.h> | |
#include <stdlib.h> | |
int stroccurs (const char* src, const char delim) { | |
int occurances = 0; | |
char c; | |
while ((c = *src++)) { | |
if (c == delim) | |
occurances++; | |
} | |
return occurances; | |
} | |
int strpos (const char* haystack, const char needle, const int start) { | |
int pos = -1, i; | |
for (i = start; i < strlen(haystack); i++) { | |
if (*(haystack+i) == needle) { | |
pos = i; | |
break; | |
} | |
} | |
return pos; | |
} | |
char *substr (const char *src, const int start, const int len) { | |
int i, j = 0; | |
char *save = (char*)malloc(sizeof(char) * (len + 1)); | |
for (i = start; i < start+len; i++) { | |
*(save+(j++)) = *(src+i); | |
} | |
*(save+len) = '\0'; | |
return save; | |
} | |
char **strsplit (const char* src, const char delim) { | |
int splits = stroccurs(src, delim), i = 0, j = 0, k = 0, len = strlen(src); | |
char *match, **matches; | |
matches = malloc(sizeof(char) * len); | |
j = strpos(src, delim, i); | |
while (j != -1 && j < len) { | |
matches[k++] = substr(src, i, j - i); | |
i = ++j; | |
j = strpos(src, delim, i); | |
} | |
matches[k++] = substr(src, i, len - i); | |
matches[k++] = NULL; | |
return matches; | |
} | |
int main(int argc, char **argv) { | |
char *PATH = "/bin:/usr/bin:/sbin:/usr/sbin:/home"; | |
int count = stroccurs(PATH, ':') + 1, i; | |
char **matches = strsplit(PATH, ':'); | |
printf("Matches: %d\n", count); | |
for (i = 0; i < count; i++) { | |
printf("Match %d: '%s'\n", i+1, matches[i]); | |
} | |
free(matches); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ gcc -std=c11 -o strtok strtok.c && ./strtok
Matches: 5
Match 1: '/bin'
Match 2: '/usr/bin'
Match 3: '/sbin'
Match 4: '/usr/sbin'
Match 5: '/home'