Tokenized substring search

  • Thread starter Generic Usenet Account
  • Start date
G

Generic Usenet Account

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;
}
}
 
E

Evan

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,591
Members
45,103
Latest member
VinaykumarnNevatia
Top