gmzorz

ft_strntok

Aug 8th, 2020
1,155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include "libft.h"
  2. #include <stdio.h>
  3.  
  4. /*
  5. **  ft_strntok - extract tokens from strings
  6. **
  7. **  <const char *str>       input string
  8. **  <const char *delim>         delimiter set
  9. **  <int count>         delimiter count, takes string before delimiter
  10. **
  11. **  Parses a string into a sequence of tokens.
  12. **  Splits based on delimiter(s) and returns sequence
  13. **
  14. **  Similar to MS-DOS FOR /F "tokens=* delims=*"
  15. */
  16.  
  17. char        *ft_strntok(const char *str, const char *delim, int count)
  18. {
  19.     char    *tokens;
  20.     int index = 0;
  21.  
  22.     tokens = (char *)ft_calloc(1, ft_strlen(str) + 1);
  23.     while (*str != '\0' && count > 0)
  24.     {
  25.         while (ft_strchr(delim, *str) == NULL)
  26.         {
  27.             tokens[index] = *str;
  28.             str++;
  29.             index++;
  30.         }
  31.         if (count == 0 || *str == '\0')
  32.             return (tokens);
  33.         while (ft_strchr(delim, *str) != NULL)
  34.         {
  35.             str++;
  36.             if (ft_strchr(delim, *str) == NULL)
  37.                 return (ft_strntok(str, delim, count - 1));
  38.         }
  39.         tokens++;
  40.         str++;
  41.     }
  42.     return (NULL);
  43. }
  44.  
  45. int     main(void)
  46. {
  47.     printf("[%s]", ft_strntok("SPLIT THIS FUCKING STRING", ' ', 2));
  48.         // 0 returns SPLIT
  49.         // 1 returns THIS
  50.         // 2 returns FUCKING
  51.         // 3 returns STRING
  52. }
Advertisement
Add Comment
Please, Sign In to add comment