what does the following statement mean?
string s="Joe Alan Smith"";
cout << (s.find("Allen") == string::npos) << endl;
Actually string::find()
returns the position of the found string, but if it doesn't find the given string, it returns string::npos
, where npos
means no position.
npos
is an unsigned integral value, Standard defines it to be -1
(signed representation) which denotes no position.
//npos is unsigned, that is why cast is needed to make it signed!
cout << (signed int) string::npos <<endl;
Output:
-1
See at Ideone : http://www.ideone.com/VRHUj
http://www.cplusplus.com/reference/string/string/npos/
As a return value it is usually used to indicate failure.
In other words, print out if the string 'Allen' was not found in the given string s
.
The .find()
method returns string::npos
if it did not find the target string within the searched string. It is an integer whose value cannot represent a "found" index value, usually -1. A valid index value is an integer >= 0 which represents the index at which the target string was found.
精彩评论