/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h> // printf
#include <stdlib.h> // malloc
// this returns an array of pointers to strings
// that is one longer than the number of strings
// the last item in the array is always NULL
// so that the caller can tell when they get to the end
// we have to do this because we have no way
// to return the size of the finished array
char **ft_split_whitespaces(char *str)
{
/*
* First count the number of pieces in the string
*/
// there will always be a NULL at the end of the array
int size = 1;
// if the string isn't empty there is one piece after the last space
if (*str != '\0')
size++;
// there will be one piece for the bit before each space
// so loop through the string looking for a space
for (char *pointer = str; *pointer != '\0'; pointer++)
if (*pointer == ' ')
size++;
/*
* Now allocate the array of items that will be returned
*/
char **array = malloc(size * sizeof(char*));
if (array == NULL) return NULL; // ERROR: return "Something really bad happened!"
/*
* Then split the string into items and store them into the array
*/
// index is where the piece will be stored
int index=0;
// we need two pointers:
// - one for where we currently are
// - and one for what we are looking for
char *current=str, *next=str;
// we are done if we are at the end of the string
while (*current != '\0')
{
// find a space character
// but stop looking if we find the end of the string instead
while (*next!='\0' && *next!=' ')
next++;
// now allocate enough space for this piece
char *piece = malloc(next - current + 1);
if (piece == NULL) break; // ERROR: exit the loop and return array as it is
// and copy the piece into the memory
for (int i=0; i<next-current; i++)
piece[i] = current[i];
// then terminate the string
piece[next-current] = '\0';
// store the new piece and increase the index
array[index++] = piece;
// now we are done with that piece
// so start looking for the enxt one
current = ++next;
}
// make sure the array ends with a NULL;
array[index] = NULL;
// return the new array
return array;
}
int main()
{
char **items = ft_split_whitespaces("Hello World This Is Me");
if (items == NULL)
printf("Something really bad happened!");
else
for (char **pointer = items; *pointer != NULL; pointer++)
printf("%s\n", *pointer);
return 0;
}