What does string::npos mean in this code?

后端 未结 12 1173
傲寒
傲寒 2020-11-30 18:50

What does the phrase std::string::npos mean in the following snippet of code?

found = str.find(str2);

if (found != std::string::npos)
    std::         


        
相关标签:
12条回答
  • 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.

    0 讨论(0)
  • 2020-11-30 19:10

    npos is just a token value that tells you that find() did not find anything (probably -1 or something like that). find() checks for the first occurence of the parameter, and returns the index at which the parameter begins. For Example,

      string name = "asad.txt";
      int i = name.find(".txt");
      //i holds the value 4 now, that's the index at which ".txt" starts
      if (i==string::npos) //if ".txt" was NOT found - in this case it was, so  this condition is false
        name.append(".txt");
    
    0 讨论(0)
  • 2020-11-30 19:13

    std::string::npos is implementation defined index that is always out of bounds of any std::string instance. Various std::string functions return it or accept it to signal beyond the end of the string situation. It is usually of some unsigned integer type and its value is usually std::numeric_limits<std::string::size_type>::max () which is (thanks to the standard integer promotions) usually comparable to -1.

    0 讨论(0)
  • 2020-11-30 19:14

    string::npos is a constant (probably -1) representing a non-position. It's returned by method find when the pattern was not found.

    0 讨论(0)
  • 2020-11-30 19:18

    size_t is an unsigned variable, thus 'unsigned value = - 1' automatically makes it the largest possible value for size_t: 18446744073709551615

    0 讨论(0)
  • 2020-11-30 19:18

    An answer for these days of C++17, when we have std::optional:

    If you squint a bit and pretend std::string::find() returns an std::optional<std::string::size_type> (which it sort of should...) - then the condition becomes:

    auto position = str.find(str2);
    
    if ( position.has_value() ) {
        std::cout << "first 'needle' found at: " << found.value() << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题