I need to split a sentence contained in a char pointer into an array of words. I've tried several methods (as I cannot use strtok. The following method I used extracts the different words, but it overwrites word already stored in the previous index in the array. What can I do? Please help.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <ctype.h>
#include <strings.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("please write a sentence\n");
return 1;
}
int i = 0, j = 0, n = 0;
char* words = argv[1];
char word[20];
string s[4];
while (words[i] != '\0')
{
// ' ' is the separator to split words
if (words[i] == '#')
{
word[j] = '\0';
s[n] = word;
j = 0;
n++;
memset(word, 0, sizeof(word));
}
else {
word[j++] = words[i];
}
i++;
}
word[j] = '\0';
/*for(int a = 0; a< n; a++)
printf("%s\n", s[a]);*/
}