Reputation: 1507
This is in a piece of C++ code I am looking through at the moment but I have never seen it before. Can someone tell me what it means? Is it just setting the bool to true if the searchText is found?
size_t startPos = searchString.find("searchText");
bool found = startPos != std::string::npos;
Upvotes: 0
Views: 227
Reputation: 10199
This snippet works in two steps:
The first line checks if the string searchText
is found within the variable searchString
(which I assume to be of std::string type). If the string is found, the method find()
will return the position where the string was found, if not it will return std::string::npos
. The result of the find()
method is stored in startPos
.
The boolean variable found
is initialized based on wheather the string was found in step #1 or not. It would have been more readable had it been written as:
bool found = (startPos != std::string::npos);
.
Note that std::string::npos
is a named constant that defined to -1
, which is the maximum possible value for size_t
(all 0xFF
s).
Upvotes: 0
Reputation: 55736
std::string::find()
returns the position of the searched substring in the given string or std::string::npos
(a constant) if the substring is not found.
Perhaps you would read the code better if it had been written that way:
size_t startPos = searchString.find("searchText");
// In the next line, '(' and ')' are not mandatory, but make this easier to read.
bool found = (startPos != std::string::npos);
That is, if startPos
is different from std::string::npos
then the substring was found.
Upvotes: 7
Reputation: 710
See http://www.cplusplus.com/reference/string/string/npos/
This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.
This actually searches a sub string in searchString and sets found to false if none is found or true if the substring exists.
Upvotes: 0
Reputation: 3911
Yep that's it. string::npos
is returned by string::find
if the substring cannot be found.
Upvotes: 0
Reputation: 61
Yes, that's exactly what it does. std::string::npos
is a static member constant value with the greatest possible value for an element of type size_t. If string::find
doesn't find the given text pattern, it returns that value.
Upvotes: 0
Reputation: 17327
Yes. std::string::npos is simply the 'biggest possible' value. If startpos
is not that, the search string must've been found.
Upvotes: 1