By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,778 Members | 1,947 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,778 IT Pros & Developers. It's quick & easy.

Tokenized substring search

P: n/a
I had a need to tokenize a string, and this is what I came up with. Is
this the most efficient way of tokenizing, or is a more efficient
solution possible?

Thanks,
Gary

#include <iostream>
#include <string>
using namespace std;
main()
{
string::size_type pos;
string cmd="a1::b1::c1::d1";
string subStr;
string token="::";
cout << "cmd string = " << cmd << endl;
try
{
for(pos=0; pos != string::npos;)
{
pos = cmd.rfind(token);
if (pos != string::npos)
{
cout << "pos = " << pos << '\n';
cmd.erase(pos);
cout << "substring cmd = " << cmd << endl;
}
else
{
throw pos;
}
} // end for
} //end try
catch(string::size_type noPos)
{
cerr << "no more tokens in cmd" << endl;
}
}

Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
There are two pre-built solutions I know of that you can use instead if
you want to avoid writing it yourself. The C standard library (and thus
C++ library) comes with strtok which will probably work but has its own
problems. Also, there is a free library (I think under a BSD-ish
licence) called Boost at boost.org that has a tokenizer that is built
using C++ features and fixes these problems.

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.