String lookup in C++: string.find() function and string::npos

Find if string a contains substring b,
not with string::size_typestrA.find(strB) > 0 pos = strA.find (strB); if(pos != string::npos){}strA.find(strB) != string:npos

int idx = str.find("abc");
if (idx == string::npos)
...
In the above code, the type of idx is defined as int, which is wrong, even if it is defined as unsigned int, it is wrong, it Must be defined as string::size_type.
npos is defined like this:
static const size_type npos = -1;

Because string::size_type (defined by the string allocator) describes size, it needs to be an unsigned integer type. Because the default configurator uses size_t as size_type, -1 is converted to an unsigned integer type, and npos becomes the largest unsigned value for that type. However, the actual value depends on the actual definition of the type size_type. Unfortunately none of these maximums are the same. In fact, (unsigned long)-1 and (unsigned short)-1 are different (provided they have different types and sizes). Therefore, the comparison formula idx == string::npos 中,如果 idx 的值为-1,由于 idx 和字符串string::npos 型别不同,比较结果可能得到 false.
The best way to tell if the result of find() is npos is to compare it directly:

if (str.find(“abc”) == string::npos) { … }

Error: if(str.find("abc"))
Note: if abc is not found, it will return -1, not 0 is True, 0 is False

Instructions:
1. If

string sub = ”abc“;
string s = ”cdeabcigld“;

The two functions s.find(sub) and s.rfind(sub) will only return the matching index if they match completely, that is, when s contains three consecutive letters of abc, the current index will be returned.

     s.find_first_of(sub),   
     s.find_first_not_of(sub),   
     s.find_last_of(sub),  
     s.find_last_not_of(sub)  

These four functions find the index in s that contains any letter in sub.

  1. If no query is found, string::npos is returned, which is a large number whose value does not need to be known.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521965&siteId=291194637