Last active
August 28, 2015 15:42
-
-
Save cirocosta/0b5fbd6f814237dc1714 to your computer and use it in GitHub Desktop.
Splits a string into char** given a delimiter
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
char** ep1sh_split_string(const char* input, unsigned* size, | |
const char delimiter) | |
{ | |
size_t input_size = strlen(input); | |
unsigned count = 0; | |
unsigned i = 0; | |
char** result = NULL; | |
char* tmp = strndup(input, input_size); | |
char* tmp_init = tmp; | |
char token_delimiter[2] = { delimiter, '\0' }; | |
while (i < input_size) { | |
while (tmp[i++] == delimiter && i < input_size) | |
; | |
while (tmp[i++] != delimiter && i < input_size) | |
; | |
count++; | |
} | |
result = malloc((count + 1) * sizeof(*result)); | |
ASSERT(result, "%s", MEM_ALOC_ERR_MSG); | |
count = 0; | |
tmp = strtok(tmp, token_delimiter); | |
while (tmp != NULL) { | |
*(result + count) = strdup(tmp); | |
ASSERT(result + count, "%s", MEM_ALOC_ERR_MSG); | |
tmp = strtok(NULL, token_delimiter); | |
count++; | |
} | |
result[count] = NULL; | |
if (size) | |
*size = count; | |
FREE(tmp_init); | |
return result; | |
} |
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
void test1() | |
{ | |
const char input[] = "/bin/ls -l"; | |
const char* expected[] = { "/bin/ls", "-l", NULL }; | |
unsigned argc = 0; | |
char** argv = NULL; | |
argv = ep1sh_split_string(input, &argc, ' '); | |
for (unsigned i = 0; i < argc; i++) | |
ASSERT(strcmp(argv[i], expected[i]) == 0, "%s != %s", argv[i], expected[i]); | |
ASSERT(argv[argc] == NULL, "Must end with a NULL"); | |
FREE_ARR(argv, argc); | |
} | |
void test2() | |
{ | |
const char input[] = " cd directory "; | |
const char* expected[] = { "cd", "directory", NULL }; | |
unsigned argc = 0; | |
char** argv = NULL; | |
argv = ep1sh_split_string(input, &argc, ' '); | |
ASSERT(argc == 2, "%d != %d", argc, 2); | |
for (unsigned i = 0; i < argc; i++) | |
ASSERT(strcmp(argv[i], expected[i]) == 0, "%s != %s", argv[i], expected[i]); | |
ASSERT(argv[argc] == NULL, "Must end with a NULL"); | |
FREE_ARR(argv, argc); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment