The function can be declared and defined the following way as it is shown in the demonstrative program.
#include <stdio.h>
#include <ctype.h>
size_t string_parser( const char *input, char *word_array[] )
{
size_t n = 0;
while ( *input )
{
while ( isspace( ( unsigned char )*input ) ) ++input;
if ( *input )
{
word_array[n++] = ( char * )input;
while ( *input && !isspace( ( unsigned char )*input ) ) ++input;
}
}
return n;
}
#define N 10
int main(void)
{
char s[] = "Hello Sam Talbot. How do you do?";
char * word_array[N];
size_t n = string_parser( s, word_array );
for ( size_t i = 0; i < n; i++ ) puts( word_array[i] );
return 0;
}
Its output is
Hello Sam Talbot. How do you do?
Sam Talbot. How do you do?
Talbot. How do you do?
How do you do?
do you do?
you do?
do?
Another approach to defining the function is to allocate dynamically the array of words inside the function. In this case the function declaration can look like
size_t string_parser( const char *input, char ***word_array )
You should at first count the words using one loop and then in another loop fill the array of words.
For example
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
size_t string_parser( const char *input, char ***word_array)
{
size_t n = 0;
const char *p = input;
while ( *p )
{
while ( isspace( ( unsigned char )*p ) ) ++p;
n += *p != '\0';
while ( *p && !isspace( ( unsigned char )*p ) ) ++p;
}
if ( n )
{
size_t i = 0;
*word_array = malloc( n * sizeof( char * ) );
p = input;
while ( *p )
{
while ( isspace( ( unsigned char )*p ) ) ++p;
if ( *p )
{
const char *q = p;
while ( *p && !isspace( ( unsigned char )*p ) ) ++p;
size_t length = p - q;
( *word_array )[i] = ( char * )malloc( length + 1 );
strncpy( ( *word_array )[i], q, length );
( *word_array )[i][length] = '\0';
++i;
}
}
}
return n;
}
int main(void)
{
char s[] = "Hello Sam Talbot. How do you do?";
char ** word_array = NULL;
size_t n = string_parser( s, &word_array );
for ( size_t i = 0; i < n; i++ ) puts( word_array[i] );
for ( size_t i = 0; i < n; i++ ) free( word_array[i] );
free( word_array );
return 0;
}
The program output is
Hello
Sam
Talbot.
How
do
you
do?