Summary
In this post, I will introduce the string
class in c++ STL. It covers useful APIs and some of my recommendations.
1. Split
2. Access
3. Comparison
4. Numeric-Conversions
Details
Split
Thanks to this post, we present the conlusions for split
first.
1. If you have access to boost, please do Solution 1.
2. You do not want to include other libraries. Implement own algorithms using Solution 2.
3. Use stream and see Solution 3.
Solutions
1. boost
#include <boost/algorithm/string.hpp>
std::string text = "Let me split this into words";
std::vector<std::string> results;
boost::split(results, text, [](char c){return c == ' ';});
Boost::split essentially performs multiple find_if on the string on the delimiter, until reaching the end.
It allows even several different delimiters
and is 60% faster than solution 3.
2. getline
char delimiter = ',';
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
3. stream
std::string text = "Let me split this into words";
std::istringstream iss(text);
std::vector<std::string> results(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>()); // only works for space
Access
Actually string
acts like vector<char>
, we recommend you use .at()
rather than []
, since .at()
check the boundary and throw exceptions.
string str = "hello";
cout << str.at(100) << endl; // libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
cout << str[100] << endl; // exit normally, print something you do not really know
Comparison
We can use !=
and ==
directly.
For <
and >
,
value | relation between compared string and comparing string |
---|---|
< 0 | Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter. |
> 0 | Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer. |
"abc" < "abcd"; // true
"abc" < "bbc" ; // true
Numeric Conversions
The functions throw a std::invalid_argument exception if the conversion is not possible and a std::out_of_range exception if the determined value is too big for the destination.
#include <cfloat>
cout << INT_MAX << endl;
cout << DBL_MAX << endl;
cout << FLT_MAX << endl;
/*
2147483647
1.79769e+308
3.40282e+38
*/
Method | Description |
---|---|
std::to_string(val) |
Converts val into a std::string . |
std::stoi(str) |
Returns an int value. |
std::stol(str) |
Returns a long value. |
std::stoll(str) |
Returns a long long value. |
std::stoul(str) |
Returns an unsigned long value. |
std::stoull(str) |
Returns an unsigned long long value. |
std::stof(str) |
Returns a float value. |
std::stod(str) |
Returns a double value. |
std::stold(str) |
Returns an long double value. |