Thread: Number of Tokens

  1. #1
    Registered User
    Join Date
    Aug 2004

    Number of Tokens


    I'm looking for a function which accepts a string as input and returns the number of the tokens of the string. Is there any ready function for this? If not, what is the correct algorithm for doing this?

    For example if string = "hello world" the function should return 2.
    If the string = "hello" it should return 1. If the string = " "(only spaces), it should return 0.

    Thank you.
    Last edited by Crashgr; 11-27-2004 at 09:31 AM.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Since your tokens are seperated by white space, you can use formatted input to count the tokens:
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    int main()
        string s = "\"I don't got time for pain. The only pain "
                   "I got time for is the pain I put on fools "
                   "who don't know what time it is!\", TTT";
        istringstream iss(s);
        string token;
        size_t num_tokens = 0;
        for (; iss.good(); num_tokens++)
            iss >> token;
        cout << num_tokens << endl;
        return 0;
    In this example, I get strings from an input stream until the stream is no longer good (there's no more strings in the stream). The same concept can be applied to other streams.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with this compiler error
    By Evangeline in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 09:27 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. Calculating next prime number
    By anilemon in forum C Programming
    Replies: 8
    Last Post: 04-17-2006, 10:38 AM
  4. Prime number program problem
    By Guti14 in forum C Programming
    Replies: 11
    Last Post: 08-06-2004, 04:25 AM
  5. Random Number problem in number guessing game...
    By -leech- in forum Windows Programming
    Replies: 8
    Last Post: 01-15-2002, 05:00 PM