strsep.c 933 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. */
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include "strsep.h"
  6. /*
  7. * Get next token from string *stringp, where tokens are possibly-empty
  8. * strings separated by characters from delim.
  9. *
  10. * Writes NULs into the string at *stringp to end tokens.
  11. * delim need not remain constant from call to call.
  12. * On return, *stringp points past the last NUL written (if there might
  13. * be further tokens), or is NULL (if there are definitely no more tokens).
  14. *
  15. * If *stringp is NULL, strsep returns NULL.
  16. */
  17. char *
  18. strsep (char **stringp, const char *delim)
  19. {
  20. char *s;
  21. const char *spanp;
  22. int c, sc;
  23. char *tok;
  24. if ((s = *stringp) == NULL)
  25. return (NULL);
  26. for (tok = s;;)
  27. {
  28. c = *s++;
  29. spanp = delim;
  30. do
  31. {
  32. if ((sc = *spanp++) == c)
  33. {
  34. if (c == 0)
  35. s = NULL;
  36. else
  37. s[-1] = 0;
  38. *stringp = s;
  39. return (tok);
  40. }
  41. }
  42. while (sc != 0);
  43. }
  44. /* NOTREACHED */
  45. }