Advertisement
avp210159

strtos() - extract WORD (token) from str (similar strtok())

Mar 6th, 2015
844
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. // avp 2015 strtos.c get WORD from char[]
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. /*
  7.  before call: *p -- ptr to start search WORD in delimiters
  8.  after call:  *p -- ptr to next char after word (and *p - word == WORD length)
  9.  returns ptr to WORD or 0
  10.  */
  11. char *
  12. strtos (char **p, const char *delim)
  13. {
  14.   char *word = 0;
  15.  
  16.   if (*((*p) += strspn(*p, delim))) {
  17.     word = *p;
  18.     (*p) += strcspn(*p, delim);
  19.   }
  20.  
  21.   return word;
  22. }
  23.  
  24. char *
  25. strdups (char **p, const char *delim)
  26. {
  27.   char *word = strtos(p, delim);
  28.  
  29.   return word ? strndup(word, *p - word) : 0;
  30. }
  31.  
  32.  
  33. #ifdef TEST
  34. #include <stdlib.h>
  35.  
  36. static inline char *
  37. strncpyz (char *dst, const char *src, int l)
  38. {
  39.   char *r = dst;
  40.  
  41.   while (l && (*r++ = *src++))
  42.     l--;
  43.   if (!l)
  44.     *r = 0;
  45.  
  46.   return dst;
  47. }
  48.  
  49. int
  50. main (int ac, char *av[])
  51. {
  52.   char *dlim = av[1] ? av[1] : (char *)" \t\r\n";
  53.   char buf[1000], *w, *ep;
  54.  
  55.   while (fputs("enter: ", stdout), fflush(stdout), fgets(buf, 1000, stdin)) {
  56. #ifdef TDUP
  57.     for (ep = buf; (w = strdups(&ep, dlim));) {
  58.       printf("[%s] ", w);
  59.       free(w);
  60.     }
  61. #else
  62.     char word[1000];
  63.     for (ep = buf; (w = strtos(&ep, dlim));)
  64.       printf("[%s] ", strncpyz(word, w, ep - w));
  65. #endif
  66.     puts("");
  67.   }
  68.  
  69.   return puts("End") == EOF;
  70. }
  71.  
  72. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement