Re: how do I split a string?
Consider using std::string for the return type, arguments and internal
representation. You can extract a char array from it anytime.
Considering errors rudimentarily to be handled by exceptions, your
routine boils down to:
#include <string>
#include <iostream>
std::string splitstring(
const std::string& teststr, // string to split
const std::string& beginstr, // start marker string
const std::string& endstr // end marker string
) {
// Locate start marker string, assumed there is no need for it
// to be prefix of teststr.
std::string::size_type p1 = teststr.find( beginstr );
if ( p1 == std::string::npos )
throw "Cannot find start marker";
p1 += beginstr.length(); // p1 points past start marker now.
// Locate end marker string, assumed there is no need for it
// to be suffix of teststr.
std::string::size_type p2 = teststr.find( endstr, p1 );
if ( p2 == std::string::npos )
throw "Cannot find end marker";
// return string between p1 and p2.
return teststr.substr( p1, p2 - p1 );
}
int main()
{
try {
std::cout
<< splitstring( "XXXXXtest:blah;YYYYY", "test:", ";" )
<< std::endl;
}
catch ( const std::string& ex ) {
std::cout << "EXCEPTION: " << ex << std::endl;
}
return 0;
}
best,
MiB.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]