Write a program that splits a string by space into words. Use an array of strings to store the words


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>
#define SIZE 100
#define LENGTH 10
void main()
{
	char str[SIZE];
    	char words[LENGTH][LENGTH]; 
    	int i,j,counter;
 
	printf("Enter  a string : ");
	gets(str);	
 
    	j=0; 
	counter=0; // is a counter in the array of strings
    	for(i=0;i<=str[i]!='\0';i++)
    	{
        	// if space or \0 encountered, the word ends and we begin with a new word
        	if(str[i]==' '||str[i]=='\0')
        	{
            		words[counter][j]='\0'; //enf the current word
            		counter++;  		//for next word
            		j=0;    		//for next word, initialize index to 0
        	}
        	else
        	{
            		words[counter][j]=str[i];
            		j++;
        	}
    	}
	words[counter++][j]='\0';

    	printf("\nList of words :\n");
    	for(i=0;i < counter;i++)
        	printf("\"%s\"\n",words[i]);
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of a stack using an array where the first element is used to contain the index of the top element