-1

Im new here so excuse me if I miss anything. I'll go straight to the point. I want to read a .txt file and store all the words inside an array of words, so what Im doing is this:

int countWords(char *stringInput)
{
char const *p = stringInput;

int count;

printf("Counting Words\n");
for (count = 0; ; ++count) {
    p = strstr(p, " ");
    if (!p)
        break;

       printf("p: %s\n",p); 
       //Here I want to store every 'word' from the 'paragraph'
       strcpy(wordsArray,p);
    p++;
}
printf("There are %d words.\n",count);
  return count;
}

The idea is that stringInput is the paragraph. I check with a printf what is being stored in p. Can I store each word on a different array? and If I can, how can I accomplish this? My problem here being that strstr doesn't just get the 'word' it gets the whole line from beginning until the next space(in this case...).

Sorry for such a beginner question. Thank you for your time and expertise.

Dro
  • 17
  • 5

1 Answers1

1

strstr just finds a substring in a string. You don't actually want to find a substring; you want to find a character, which is computationally simpler. So if you just wanted to find the space, you should use strchr instead.

But if you want to split the string into individual pieces, you might want to use strtok.

All of those functions are well-described in their manpages. (man strchr; man strtok), which you should be able to read on your own machine. But they are available online if you prefer to use the internet rather than a locally-available resource.

rici
  • 234,347
  • 28
  • 237
  • 341