Please help in understand code:

I am writing below mentioned function to find the frequency of substring in file:

can someone help me understand use of : if(a.find(b,0) != std::string::npos)

unsigned short numString (string a, string b)
{
unsigned short temp=0;
if(a.find(b,0) != std::string::npos) {
temp++;
}
return temp;

}
http://en.cppreference.com/w/cpp/string/basic_string/find

Look for string b in a, starting at offset 0 in a.

If the string isn't found, find returns std::string::npos, otherwise it returns the offset in string a where string b appears.
find returns the position of the string in which the substring was found, specifically, a std::string::size_type. The problem is: What position means that the substring was not found?

The answer is to return the maximum value of std::string::size_type. This value may be different on different computers, so std::string::npos represents that value.

std::string::npos is larger than the max length of a string, so that if statement basically says:
"if the position the substring was found is less than beyond the max length of the string..."
Last edited on
Topic archived. No new replies allowed.