Search code examples
cfor-loopwhile-loopc-stringsstrtok

how to determine last words of each string?


I have this assignment:

Enter a sequence of sentences from the keyboard into the string array (the end of entering - empty string). Determine the last word of each of these sentences.

The problem is that my program outputs the last word of the last sentence, and I need the last word of each sentence to be output.

Program I have tried:

#include <stdio.h>
#include <string.h>

int main() {
   char str[10][100];
   int i;

   printf("Enter a sequence of sentences:\n");

   for (i = 0; i < 10; i++) {
       if (*gets(str) == '\0')
          break;
   }

   printf("The last word of each of these sentences is:\n");
 
   for (i = 0; i < 10; i++) {
       char *word;
       word = strtok(str[i], ".");
       while (word != NULL) {
           char *last_word = word;
           word = strtok(NULL, ".");
       }
       printf("%s\n", last_word);
   }

   return 0;
}

Solution

  • The delimiter in this call

    word = strtok(str[i], ".");
    

    does not make sense.

    It seems you mean

    word = strtok(str[i], " \t.");
    

    provided that a sentence can be ended only with a dot and words are separated by spaces or tab characters.

    Another problem is that the variable last_word must be declared before the while loop.

    For example

       char *last_word = NULL;
       char *word;
       word = strtok(str[i], " \t.");
       while (word != NULL) {
           last_word = word;
           word = strtok(NULL, " \t.");
       }
    

    And it is better to use for loop instead of the while loop

       char *last_word = NULL;
    
       for ( char *word = strtok(str[i], " \t." );
             word != NULL;
             word = strtok(NULL, " \t.") ) 
       {
           last_word = word;
       }
    

    Pay attention to that the function gets is unsafe and is not supported by the C Standard. Instead use standard C function fgets.

    And the condition in the second for loop

    for(i=0; i<10; i++)
    {
        char *word;
        //...
    

    is incorrect because the user can enter less than 10 sentences.