-
Number of Tokens
Hello!!
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.
-
Since your tokens are seperated by white space, you can use formatted input to count the tokens:
Code:
#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;
}//main
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.
gg