Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. include <stdlib.h>
  2.  
  3. int ft_is_whitespace(char c)
  4. {
  5. if (c == '\t' || c == '\n' || c == ' ')
  6. return (1);
  7. else
  8. return (0);
  9. }
  10.  
  11. int ft_word_count(char *str)
  12. {
  13. int i;
  14. int chr;
  15.  
  16. if (*str == '\0')
  17. return (0);
  18. i = 0;
  19. chr = 0;
  20. while (*str)
  21. {
  22. if (ft_is_whitespace(*str))
  23. {
  24. str++;
  25. chr = 0;
  26. }
  27. else
  28. {
  29. if (chr == 0)
  30. i++;
  31. chr = 1;
  32. str++;
  33. }
  34. }
  35. return (i);
  36. }
  37.  
  38. char **ft_allocate_memory(char *str, int word_count, int i, int j)
  39. {
  40. char **arr;
  41.  
  42. arr = (char**)malloc(sizeof(char*) * (word_count + 1));
  43. if (*str == '\0' && ((arr[0] = 0) || 1))
  44. return (arr);
  45. while (ft_is_whitespace(*str))
  46. str++;
  47. while (*str)
  48. {
  49. if (ft_is_whitespace(*str))
  50. {
  51. arr[i++] = (char*)malloc(sizeof(char) * (j + 1));
  52. while ((j = 0) || ft_is_whitespace(*str))
  53. str++;
  54. str--;
  55. }
  56. else
  57. j++;
  58. if (*(str++ + 1) == '\0')
  59. arr[i] = (char*)malloc(sizeof(char) * (j + 1));
  60. }
  61. if (!(ft_is_whitespace(*(str - 1))))
  62. i++;
  63. arr[i] = 0;
  64. return (arr);
  65. }
  66.  
  67. char **ft_split_whitespaces(char *str)
  68. {
  69. int i;
  70. int j;
  71. int word_count;
  72. char **arr;
  73.  
  74. i = 0;
  75. j = 0;
  76. word_count = ft_word_count(str);
  77. arr = ft_allocate_memory(str, word_count, 0, 0);
  78. while (ft_is_whitespace(*str))
  79. str++;
  80. while (i < word_count)
  81. {
  82. if (ft_is_whitespace(*str))
  83. {
  84. while (ft_is_whitespace(*str))
  85. str++;
  86. arr[i][j] = '\0';
  87. i += (j != 0) ? 1 : 0;
  88. j = 0;
  89. }
  90. else
  91. arr[i][j++] = *str++;
  92. }
  93. return (arr);
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement