discodowney
discodowney

Reputation: 1507

Line of code that I have never seen before

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

Answers (7)

shauzi158
shauzi158

Reputation: 1

It's a function in the windows.h library.

Upvotes: -1

Bhargav
Bhargav

Reputation: 10199

This snippet works in two steps:

  1. 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.

  2. 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 0xFFs).

Upvotes: 0

ereOn
ereOn

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

Gottox
Gottox

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

Gordon Bailey
Gordon Bailey

Reputation: 3911

Yep that's it. string::npos is returned by string::find if the substring cannot be found.

Upvotes: 0

thorsten
thorsten

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

xxbbcc
xxbbcc

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

Related Questions