Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <alloca.h>
- #include <assert.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char **strtoknize(const char *str, size_t slen, const char *dlmt, int dlen, int *n_toks)
- {
- char *toks = alloca(slen);
- char *save_ptr = NULL;
- char *ptr = NULL;
- int i;
- char **buffer = NULL;
- strncpy(toks, str, slen);
- if (!strcmp(&toks[slen - dlen], dlmt)) {
- toks[slen - dlen] = '\0';
- }
- i = 0;
- ptr = strtok_r(toks, dlmt, &save_ptr);
- while (ptr) {
- i++;
- buffer = realloc(buffer, sizeof (char **) * i);
- assert(buffer);
- buffer[i - 1] = strdup(ptr);
- assert(buffer[i - 1]);
- ptr = strtok_r(NULL, dlmt, &save_ptr);
- }
- *n_toks = i;
- return buffer;
- }
- int main(void)
- {
- char **buffer;
- int i;
- int n_toks;
- #define STR "foo||bar||tar||zar||"
- buffer = strtoknize(STR, strlen(STR),
- "||", 2, &n_toks);
- for (i = 0; i < n_toks; i++) {
- puts(buffer[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment