liftchampion

SPLIT WHITESPACES

Oct 30th, 2018
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include <stdlib.h>
  2.  
  3. int             ft_is_space(char c)
  4. {
  5.     if ((c >= 9 && c <= 13) || c == 32)
  6.         return (1);
  7.     return (0);
  8. }
  9.  
  10. unsigned int    ft_count_words(char *str)
  11. {
  12.     int c;
  13.     int was_space;
  14.  
  15.     c = 0;
  16.     was_space = 1;
  17.     while (*str && ft_is_space(*str))
  18.     {
  19.         str++;
  20.     }
  21.     while (*str)
  22.     {
  23.         if (!ft_is_space(*str) && was_space)
  24.             c++;
  25.         was_space = ft_is_space(*str);
  26.         str++;
  27.     }
  28.     return (c);
  29. }
  30.  
  31. unsigned int    ft_strlen(char *str, int delim_by_spaces)
  32. {
  33.     unsigned int len;
  34.  
  35.     len = 0;
  36.     while (*str && (!delim_by_spaces || !ft_is_space(*str)))
  37.     {
  38.         len++;
  39.         str++;
  40.     }
  41.     return (len);
  42. }
  43.  
  44. unsigned int    ft_strlcpy(char *dest, char *src, unsigned int size)
  45. {
  46.     unsigned int i;
  47.  
  48.     i = 0;
  49.     while (src[i] != '\0' && i < size - 1 && !ft_is_space(*src))
  50.     {
  51.         dest[i] = src[i];
  52.         i++;
  53.     }
  54.     dest[i] = '\0';
  55.     return (ft_strlen(src, 0));
  56. }
  57.  
  58. char            **ft_split_whitespaces(char *str)
  59. {
  60.     char            **strs;
  61.     int             was_space;
  62.     unsigned int    i;
  63.  
  64.     was_space = 1;
  65.     i = 0;
  66.     strs = (char**)malloc(sizeof(char*) * ft_count_words(str) + 1);
  67.     if (!strs)
  68.         return (0);
  69.     strs[ft_count_words(str)] = 0;
  70.     while (*str)
  71.     {
  72.         if (was_space && !ft_is_space(*str))
  73.         {
  74.             strs[i] = (char*)malloc(sizeof(char) * ft_strlen(str, 1) + 1);
  75.             ft_strlcpy(strs[i++], str, ft_strlen(str, 1) + 1);
  76.         }
  77.         was_space = ft_is_space(*str);
  78.         str++;
  79.     }
  80.     return (strs);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment