开发者

What does string::npos mean? [duplicate]

开发者 https://www.devze.com 2023-02-13 04:56 出处:网络
This question already has answers here: What does string::npos mean in this code? (12 answers) 开发者_如何学Python
This question already has answers here: What does string::npos mean in this code? (12 answers) 开发者_如何学Python Closed 9 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消