文字列内のnpos



Npos String



STLのstring.find()関数のプロトタイプは次のとおりです。

size_t find (const string& str, size_t pos = 0) const noexcept size_t find (const char* s, size_t pos = 0) const size_t find (const char* s, size_t pos, size_type n) const size_t find (char c, size_t pos = 0) const noexcept

戻り値はsize_t型です。
見つかった場合は、文字または文字列の添え字が返されます。見つからない場合は?
nposビットはSTLで使用され、見つからないことを示します。当局がこの変数をどのように解釈するかを見てみましょう。



std::string::npos static const size_t npos = -1 Maximum value for size_t npos is a static member constant value with the greatest possible value for an element of type size_t. This value, when used as the value for a len (or sublen) parameter in string's member functions, means 'until the end of the string'. As a return value, it is usually used to indicate no matches. This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type. Chinese: The maximum size_t npos is a static member constant value whose value is the largest possible value for elements of type size_t. When this value is used as the value of the len (or sublen) parameter in the string member function, it means 'until the end of the string'. As a return value, it is usually used to indicate a mismatch. The value of this constant is-1, This is because size_t is an unsigned integer, which is the largest representable value of this type.

次のように使用します。

std::string s1 = 'hello world!' if(s1.find('o') != std::string::npos){ std::cout<<'Find letter o'<< std::endl }else{ std::cout<<'The letter o was not found'<< std::endl }