ft_strsplit.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_strsplit.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: mazimi <mazimi@student.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2014/12/08 19:26:52 by mazimi #+# #+# */
  9. /* Updated: 2017/01/31 12:55:00 by mazimi ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "../libft.h"
  13. static int ft_count_words(const char *s, char c)
  14. {
  15. int sp;
  16. int sp_tmp;
  17. sp_tmp = 0;
  18. sp = 0;
  19. while (*s)
  20. {
  21. if (sp_tmp == 1 && *s == c)
  22. sp_tmp = 0;
  23. if (sp_tmp == 0 && *s != c)
  24. {
  25. sp_tmp = 1;
  26. sp++;
  27. }
  28. s++;
  29. }
  30. return (sp);
  31. }
  32. char **ft_strsplit(char const *s, char c)
  33. {
  34. int sp;
  35. char **tab;
  36. int i;
  37. int j;
  38. int start;
  39. if (s == NULL || c == 0)
  40. return (NULL);
  41. sp = ft_count_words(s, c);
  42. tab = malloc((sizeof(char *) * (sp + 1)));
  43. i = 0;
  44. j = -1;
  45. while (++j < sp)
  46. {
  47. while (s[i] && s[i] == c)
  48. i++;
  49. start = i;
  50. while (s[i] && s[i] != c)
  51. i++;
  52. tab[j] = ft_strsub(s, start, i - start);
  53. i++;
  54. }
  55. tab[j] = NULL;
  56. return (tab);
  57. }