gettok() && strtoi()

By Sonny on Apr 24, 2010

A very basic gettok() function i made from scratch for a contest.It's not to be used with loops, since it uses substr. Hasn't been fully tested, but works as needed in my experience. Post bugs, if you find any. I'll probably finish all the other tokens, if and when I have time.

gettok() usage:

gettok("calm your cooter down!", " ", 3)
//returns cooter

gettok("", ".", 4)
//returns test

strtoi() usage:

strtoi(gettok("hello world", " ", 0))
// returns the total number of tokens as an integer (instread of a string)

typedef unsigned int uint;

int strtoi(string a)
  int i;
  istringstream b(a);
  b >> i;
  return i;

string gettok(string tokens, string delim, int token)
  int toks = 0, tl, tp;
  string t;
  tokens = tokens.insert(tokens.length(), delim);
  for (uint i = 1;i<=tokens.length();++i)
    string s = tokens.substr(i-1,1);
    if (s == delim)
      toks = toks+1;
      if (toks < token)
        tp = i;
    if (toks == token && token != 0)
      tp = i-tp;
      tl = tp;
      t = tokens.substr(i-tp,tl);

  stringstream a;
  a << toks;
  t = (token == 0) ? a.str() : t.substr(0,t.length()-1);
  return t;


Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.