简体   繁体   中英

String find function in C++ returns 0 if string passed as argument is empty


When a empty string is passed to find function it returns 0.
If uninitialized string is passed, then also it returns 0.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1="";
    string str2="This is a sample string";
    unsigned int loc = str2.find(str1);
    cout << "Loc : " << loc << endl;
    if(loc != string::npos)
    {
        cout << "Found" << endl;
    }
    else
    {
        cout << "Not found" << endl;
    }
    return 0;
}

Output :
Loc: 0
Found

My question is why does find return 0 instead of returning string::npos?

A needle l can be found in position i of haystack h if i + len(l) <= len(h) and for all 0 <= k < len(l) we have l[k] == h[i+k] . What you're dealing with is simply the vacuous truth of this definition: 'for all x ' automatically becomes true if there's no valid x to begin with.

As the docs on cppreference say. (Emphasis is mine.)

Finds the first substring equal to the given character sequence. Search begins at pos, ie the found substring must not begin in a position preceding pos.

  1. Finds the first substring equal to str .

When is a string found at a position?

Formally, a substring str is said to be found at position xpos if all of the following is true:

  • xpos >= pos
  • xpos + str.size() <= size()
  • for all positions n in str , Traits::eq(at(xpos+n), str.at(n))

An empty string fulfills these requirements at position 0.

The docs further say. (Emphasis is mine.)

In particular, this implies that

  • a substring can be found only if pos <= size() - str.size()
  • an empty substring is found at pos if and only if pos <= size()
  • for a non-empty substring, if pos >= size() , the function always returns npos .

It found the exact match at position 0 (the first one searched), so that index is returned.

Quoting from cppreference , the conditions are:

Formally, a substring str is said to be found at position xpos if all of the following is true:

  1. xpos >= pos
  2. xpos + str.size() <= size()
  3. for all positions n in str , Traits::eq(at(xpos+n), str.at(n))

Trying to match substring from position 0, we get that

  1. is met, because 0 (our search position) >= 0 (start parameter)
  2. is met, because 0 + 0 <= size()
  3. is met, because there is no character in the needle that doesn't match the corresponding character in haystack - all of them match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM