Last active
December 25, 2019 07:37
-
-
Save border/8317976 to your computer and use it in GitHub Desktop.
using strtok in c
http://stackoverflow.com/questions/8106765/using-strtok-in-c
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> | |
char** tokenize(const char* input) | |
{ | |
printf("%s\n", input); | |
char* str = strdup(input); | |
int count = 0; | |
int capacity = 10; | |
char** result = (char **)malloc(capacity*sizeof(*result)); | |
char* tok=strtok(str,"/"); | |
while(1) | |
{ | |
if (count >= capacity) { | |
result = (char **)realloc(result, (capacity*=2)*sizeof(*result)); | |
} | |
result[count++] = tok? strdup(tok) : tok; | |
if (!tok) { | |
break; | |
} | |
tok=strtok(NULL,"/"); | |
} | |
free(str); | |
return result; | |
} | |
int main () | |
{ | |
char** tokens = tokenize("/execlient//master1/node1//test1/"); | |
char *path = (char *)malloc(128); | |
char** it; | |
memset(path, '\0', 128); | |
for(it=tokens; it && *it; ++it) | |
{ | |
if (*it != NULL) { | |
if (path == NULL) { | |
printf("path is null %s\n", *it); | |
sprintf(path, "/%s", *it); | |
} else { | |
sprintf(path, "%s/%s", path, *it); | |
} | |
printf("path: %s\n", path); | |
free(*it); | |
} | |
} | |
free(path); | |
free(tokens); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment