0

i'm trying to get the last word of the sentence using strtok.. i tried this :

while (tok != NULL)
  {
    tok = strtok (NULL, " ");
    if((tok != NULL) && (strtok(NULL, " ")==NULL))
            printf("%s", tok);
  }

kinda doesn't work... anyone knows why?
Yes, tok is a char * pointer..

3
Contributors
6
Replies
7
Views
9 Years
Discussion Span
Last Post by Nick Evan
0

>>anyone knows why?
Yes.

how about something like this:

char* lastWord = NULL;
while( tok != NULL )
{
   lastWord = tok;
   tok = strtok(NULL, " ");
}
printf("%s\n", lastWord);
0

you might have to add code to bypass all other white space (spaces and tabs) because I don't think strtok will do that. Example:

"No     is        the          time       "
0

kinda doesn't work... anyone knows why?

[edit] AD solved that problem already [/edit]

Anyway, if you're using C++, why not use std::strings, find() and substr()?
Demo:

#include <iostream>
#include <string>

int main ()
{
  std::string str = "This is a line of text";
  int lastspace= str.find_last_of(' ')  ;
  std::cout << str.substr(lastspace+1 ,str.size()-lastspace ) << "\n";
  return 0;
}

output: text

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.