Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C tokenizer

Status
Not open for further replies.

jl3574

Programmer
Jun 5, 2003
76
0
0
CA
i have a simple question.
how do i get the 4th token of a line using tokenizer?
if a char string[]="first second third fourth fifth"
i want to pull out "fourth"
 
One quick way would be
Code:
char token[100];
sscanf(string,"%*s%*s%*s%s",token);

--
 
Only caveat with gnu compiler for the strtok is a missing token ie one,,two,three

man strtok has a blurb about the situation.
 
Or try this ad hoc (freeware;) improvisation:
Code:
#include <string.h>
/* Useful helper function */
const char* SkipToken(const char* str)
{
  const char* p;
  if (!str)
    return 0;
  while (*str == ' ')
    ++str;
  if (*str == 0)
    return 0;
  p = strchr(str,' ');
  return p?p:str + strlen(str);
}
/* Nth from Zero (it's C;); toksz <= 0 - no size check.
 * Returns (almost useless) pointer to str (not to tok)
 * or NULL if no such token...
 */
const char* GetNthToken(const char* str, int n, char* tok, int toksz)
{
  int len;
  const char* q;
  const char* p = str;

  while (n-->0)
    p = SkipToken(p);
  if (p)
  {
    while (*p == ' ')
      ++p;
    if (*p == 0)
      return 0;
    if (!tok)
      return p;
    q = strchr(p,' ');
    len = (q?q-p:strlen(p));
    if (toksz <= 0 || len < toksz)
    {
      memmove(tok,p,len);
      tok[len] = 0;
    }
    else
      tok[0] = 0;
  }
  return p;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top