The type and value of “npos” are a big pitfall for the use of strings. Be very careful that you always use string::size_type, not int or unsigned, for the return type when you want to check the return value of a find function. Otherwise, the comparison with string::npos might not work.
template <typename charT, typename traits = char_traits<charT>, typename Allocator = allocator<charT> >
class basic_string {
public:
typedef typename Allocator::size_type size_type;
...
static const size_type npos = -1;
...
};
For example:
int idx = s.find("hi"); // assume npos is returned
if(idx == string::npos) // ERROR: comparison might not work think...there is type conversion here
{
...
}
We should code as below:
string:size_type idx = s.find("hi");
if(idx == string::npos)
{
...
}
(2) Main new features in C++11
a. Strings now provide convenience functions to convert strings to numeric values and vice versa
b. Strings now support move semantics and initializer list
c. u16string and u32string are predefined (plus string and wstring)
d. Strings are now indirectly required to provide an end-of-string character (’\0’ for string) because for a string s, s[s.length()] is always valid and s.data() returns the characters including a trailing end-of-string character
e. Reference-counted implementations of string classes are no longer supported
f. Strings now provide front() and back() to access the first or last element and shrink_to_fit to shrink capacity