Created
October 27, 2017 19:13
-
-
Save karimamd/1c1cac76cd1dec968bbc6ced1f2a6011 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 <assert.h> | |
char** str_split(char* a_str, const char a_delim) | |
{ | |
char** result = 0; | |
size_t count = 0; | |
char* tmp = a_str; | |
char* last_comma = 0; | |
char delim[2]; | |
delim[0] = a_delim; | |
delim[1] = 0; | |
/*Count how many elements will be extracted. */ | |
while (*tmp) | |
{ | |
if (a_delim == *tmp) | |
{ | |
count++; | |
last_comma = tmp; | |
} | |
tmp++; | |
} | |
/* Add space for trailing token. */ | |
count += last_comma < (a_str + strlen(a_str) - 1); | |
/* Add space for terminating null string so caller | |
knows where the list of returned strings ends. */ | |
count++; | |
result = malloc(sizeof(char*) * count); | |
if (result) | |
{ | |
size_t idx = 0; | |
char* token = strtok(a_str, delim); | |
while (token) | |
{ | |
assert(idx < count); | |
*(result + idx++) = strdup(token); | |
token = strtok(0, delim); | |
} | |
assert(idx == count - 1); | |
*(result + idx) = 0; | |
} | |
return result; | |
} | |
int main() | |
{ | |
char commandParts[] = "ls -l & kareem"; | |
char** tokens; | |
printf("commandParts=[%s]\n\n", commandParts); | |
tokens = str_split(commandParts, ' '); | |
if (tokens) | |
{ | |
int i; | |
for (i = 0; *(tokens + i); i++) | |
{ | |
printf("command parts=[%s]\n", *(tokens + i)); | |
free(*(tokens + i)); | |
} | |
printf("\n"); | |
free(tokens); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment