Is there a class or function in c++ that is similar to the StringTokenizer class or the split() method?
Printable View
Is there a class or function in c++ that is similar to the StringTokenizer class or the split() method?
How about:
Code:std::vector< std::string > Split( const std::string &string, const std::string &delim = " " )
{
std::vector< std::string > result;
std::string substr;
for( unsigned int n = 0; n < string.size(); ++n )
{
if( delim.find_first_of( string[ n ] ) == std::string::npos )
substr.push_back( string[ n ] );
else if( substr.size() > 0 )
{
result.push_back( substr );
substr.clear();
}
}
if( substr.size() > 0 )
result.push_back( substr );
return result;
}
Where can I find functions like this? I normally look at Strings library - C++ Reference but more often than not a function I need isn't listed and I have to ask on a forum. Also, are there wrapper classes like in Java? Something I could use to say like
bool Character.isUpperCase(char ch)
bool Character.isDigit(char ch)
int Integer.parseInt(String s)
Btw, I look at the whole reference. I just had the string library brought up atm.
string is a wrapper ;)
Code:
bool isUpperCase(char ch)
{
return ch >= 'A' && ch <= 'Z';
}
bool isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
int Integer.parseInt(String s) // you can use _atoi for this
See isupper, isdigit and boost::lexical_cast. For the latter you can also use stringstream and things like sscanf if you choose to go a more C way.
this is the code that I use for tokenizing strings:
but it assumes only 1 delimiter, and as such, may not suit your needs.Code:void TokenizeString(const std::string& str, char delim, std::vector<std::string>& v_string)
{
std::stringstream ss(str);
std::string token;
v_string.clear();
while (std::getline(ss, token, delim)
{
v_string.push_back(token);
}
}