Eitan Seri-Levi Eitan Seri-Levi - 3 months ago 34
C Question

splitting a string by white spaces

Before reading this question please note that my question pertains to a school assignment. For this assignment the only function we are allowed to use is malloc(). Everything else must be done without the use of other libraries.

I'm calling a function ft_split_whitespaces. This function takes a string as input and "splits" it into words. Words are separated spaces, tabs and line breaks.

#include <stdio.h>

char **ft_split_whitespaces(char *str);

int main(void)
{
char *str = "what is";
char **test = ft_split_whitespaces(str);

}


With respect to the example above the result at each index should be

test[0] = "what"
test[1] = "is"
test[2] = NULL


However, I am only able to print the results of test[0]. All other indices do not get printed to display. Heres an example of some code that I assume should print the results of my function.

int i = 0;
while(test[i] != NULL)
{
printf("%s", test[i]);
i++;
}


When this portion of code is ran, only test[0] is printed to the output. I've been sitting here trying to debug my code for hours. If anyone has some spare time and doesn't mind looking over my code, I'd appreciate it tremendously. I have a feeling it may be an issue with how I'm using malloc, but I still cant figure it out.

#include <stdlib.h>
#include <stdio.h>


int count_whitespaces(char *str)
{
int space_count;
int i;

space_count = 0;
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == 9 || str[i] == '\n')
{
if(str[i+1] != ' ' && str[i+1] != 9 && str[i+1] != '\n')
space_count++;
}
i++;
}
return (space_count);
}

int check_whitespace(char c)
{
if (c == ' ' || c == 9 || c == '\n' || c == '\0')
{
return (1);
}
else
return(0);
}

int count_characters(char *str, int i)
{
int char_count;

char_count = 0;
while(str[i])
{
if(str[i+1] != ' ' && str[i+1] != 9 && str[i+1] != '\n')
char_count++;
else
break;
i++;
}
return (char_count);
}

char **ft_split_whitespaces(char *str)
{
int i;
int j;
int k;
char **word;
int space;

i = 0;
j = 0;
k = 0;
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
if((word[j] = malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL)
return (NULL);
while (check_whitespace(str[i]) == 0)
{
word[j][k] = str[i];
i++;
k++;
}
j++;
}
}
j++;
word[j] = NULL;
j = 0
return word;
}

Answer

You forgot to reset k. The outer while loop in ft_split_whitespaces should look like that

  while (str[i] != '\0') {
    if (check_whitespace(str[i]) == 1){
      i++;
    }
    else {
      if ((word[j] =
           malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL){
        return (NULL);
      }
      while (check_whitespace(str[i]) == 0) {
        word[j][k] = str[i];
        i++;
        k++;
      }
      word[j][k] = '\0';
      j++;
      k = 0;             // reset k
    }
  }