home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / STPTOK.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  83 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  stptok() -- public domain by Ray Gardner, modified by Bob Stout
  5. **
  6. **   You pass this function a string to parse, a buffer to receive the
  7. **   "token" that gets scanned, the length of the buffer, and a string of
  8. **   "break" characters that stop the scan.  It will copy the string into
  9. **   the buffer up to any of the break characters, or until the buffer is
  10. **   full, and will always leave the buffer null-terminated.  It will
  11. **   return a pointer to the first non-breaking character after the one
  12. **   that stopped the scan.
  13. */
  14.  
  15. #include <string.h>
  16. #include <stdlib.h>
  17. #include "snip_str.h"
  18.  
  19. #if defined(__cplusplus) && __cplusplus
  20.  extern "C" {
  21. #endif
  22.  
  23. char *stptok(const char *s, char *tok, size_t toklen, char *brk)
  24. {
  25.       char *lim, *b;
  26.  
  27.       if (!*s)
  28.             return NULL;
  29.  
  30.       lim = tok + toklen - 1;
  31.       while ( *s && tok < lim )
  32.       {
  33.             for ( b = brk; *b; b++ )
  34.             {
  35.                   if ( *s == *b )
  36.                   {
  37.                         *tok = 0;
  38.                         for (++s, b = brk; *s && *b; ++b)
  39.                         {
  40.                               if (*s == *b)
  41.                               {
  42.                                     ++s;
  43.                                     b = brk;
  44.                               }
  45.                         }
  46.                         return (char *)s;
  47.                   }
  48.             }
  49.             *tok++ = *s++;
  50.       }
  51.       *tok = 0;
  52.       return (char *)s;
  53. }
  54.  
  55. #if defined(__cplusplus) && __cplusplus
  56.  }
  57. #endif
  58.  
  59. #ifdef TEST
  60.  
  61. #include <stdio.h>
  62.  
  63. main(int argc, char *argv[])
  64. {
  65.       char *ptr, buf[256];
  66.  
  67.       if (3 > argc)
  68.       {
  69.             puts("Usage: STPTOK \"string\" \"token_string\"");
  70.             return EXIT_FAILURE;
  71.       }
  72.       else  ptr = argv[1];
  73.       do
  74.       {
  75.             ptr = stptok(ptr, buf, sizeof(buf), argv[2]);
  76.             printf("stptok(\"%s\", \"%s\")\n  buf: \"%s\"\n  "
  77.                   "returned: \"%s\"\n", argv[1], argv[2], buf, ptr);
  78.       } while (ptr && *ptr);
  79.       return EXIT_SUCCESS;
  80. }
  81.  
  82. #endif /* TEST */
  83.