ft_strsplit.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_strsplit.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@students.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2015/11/29 02:25:46 by bchanot #+# #+# */
  9. /* Updated: 2016/09/13 12:32:37 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libft.h"
  13. #include <stdlib.h>
  14. static int ft_cpt(char const *s, char c)
  15. {
  16. int cpt;
  17. int cpt2;
  18. cpt = 0;
  19. cpt2 = 0;
  20. while (s[cpt])
  21. {
  22. while (s[cpt] == c && s[cpt])
  23. cpt++;
  24. if (s[cpt] != c && s[cpt])
  25. cpt2++;
  26. while (s[cpt] != c && s[cpt])
  27. cpt++;
  28. }
  29. return (cpt2);
  30. }
  31. static int ft_word_len(char const *s, char c)
  32. {
  33. int len;
  34. len = 0;
  35. while (s[len] != c && s[len])
  36. len++;
  37. if (!len)
  38. len++;
  39. return (len);
  40. }
  41. char **ft_strsplit(char const *s, char c)
  42. {
  43. char **t_str;
  44. int word;
  45. int i;
  46. word = 0;
  47. i = 0;
  48. if (!s)
  49. return (NULL);
  50. t_str = (char **)malloc(sizeof(char *) * (ft_cpt(s, c) + 1));
  51. if (!t_str)
  52. return (NULL);
  53. while (s[i])
  54. {
  55. if (s[i] == c)
  56. i++;
  57. else
  58. {
  59. t_str[word] = ft_strsub(&s[i], 0, ft_word_len(&s[i], c), 0);
  60. i = i + ft_word_len(&s[i], c);
  61. word++;
  62. }
  63. }
  64. t_str[word] = NULL;
  65. return (t_str);
  66. }