Thread: Getting the last word from a string using strtok?

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    6

    Getting the last word from a string using strtok?

    I'm trying to get the last word from each line in a file using strtok(). I know how to step through each line in the file but I am having trouble getting the last word of the line.

    The line looks like this:
    Code:
    ROOM NAME: Room
    so far I have this:
    Code:
    char *token = strtok(line, " ");
    while (token != NULL)
    {
    printf("%s\n", token); token = strtok(NULL, " ");
    }
    The output:
    Code:
    ROOM
    NAME:
    Room
    I'm printing out each word to see what I'm doing. Ultimately I would like to store the last word in a variable. I'm just not sure how to get the last word.

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,643
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        FILE *f = fopen("data.txt", "r");
        char line[1000];
    
        while (fgets(line, sizeof line, f) != NULL) {
            char *last_tok = NULL;
            char *tok = strtok(line, " \t\n");
            while (tok) {
                last_tok = tok;
                tok = strtok(NULL, " \t\n");
            }
            if (last_tok)
                printf("%s\n", last_tok);
        }
    
        fclose(f);
    
        return 0;
    }

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    > The line looks like this:

    Which suggests that a naive approach will quickly become obsolete. The line you posted suggests a specific file format, and in my experience the very next requirement added will be introspection of the first part. Instead of simply grabbing the last "word", I'd favor a proper tokenization of the file using knowledge of the format such that your tokens become ["ROOM NAME", "Room"].

    In other words, as a start, separate the line on a colon and store the two parts (after trimming, of course) into a suitable data structure.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Word sort using strtok
    By programmerc in forum C Programming
    Replies: 10
    Last Post: 12-21-2012, 11:35 AM
  2. How to reverse a string word by word?
    By SuperMiguel in forum C Programming
    Replies: 22
    Last Post: 03-29-2012, 12:40 AM
  3. Simple Removal of string in string via strtok.
    By Vincent Wouters in forum C Programming
    Replies: 6
    Last Post: 11-11-2011, 01:48 PM
  4. strtok help on a word frequency program
    By steafo in forum C++ Programming
    Replies: 2
    Last Post: 07-25-2010, 09:17 PM
  5. strtok - word counting from a file
    By |PiD| in forum C Programming
    Replies: 4
    Last Post: 11-15-2002, 04:16 AM

Tags for this Thread