I am trying to create a function that takes a string
, splits it into words
and return an array
with the words
in it. I am not allowed to use any pre-made functions other than malloc
within the splitting
function. Finally I have to set my function in this form char **ft_split_whitespaces(char *str)
My current output looks like that:
d this is me
s is me
s me
r
Expected output:
Hello
World
This
Is
Me
my full code is in the following codes:
#include <stdio.h>
#include <stdlib.h>
int count_words(char *str)
{
int i;
int word;
i = 0;
word = 1;
while(str[i]!='\0')
{
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t'
|| str[i]=='\f' || str[i]=='\r' || str[i]=='\v')
word++;
i++;
}
return (word);
}
char **ft_split_whitespaces(char *str)
{
int index;
int size;
int index2;
char **arr;
index = 0;
index2 = 0;
size = count_words(str);
arr = (char **)malloc(size * sizeof(char));
if (arr == NULL)
return ((char **)NULL);
while (str[index])
{
if(str[index] == ' ')
{
index++;
value++;
index2++;
}
else
*(arr+index2) = (char*) malloc(index * sizeof(char));
*(arr+index2) = &str[index];
index++;
}
**arr = '\0';
return (arr);
}
int main()
{
char a[] = "Hello World This Is Me";
char **arr;
int i;
int ctr = count_words(a);
arr = ft_split_whitespaces(a);
for(i=0;i < ctr;i++)
printf("%s\n",arr[i]);
return 0;
}