Does an empty string contain an empty string in C++?

后端 未结 7 1428
渐次进展
渐次进展 2021-01-03 00:53

Just had an interesting argument in the comment to one of my questions. My opponent claims that the statement \"\" does not contain \"\"<

7条回答
  •  情深已故
    2021-01-03 01:44

    Today I had the same question since I'm currently bound to a lousy STL implementation (dating back to the pre-C++98 era) that differs from C++98 and all following standards:

    TEST_ASSERT(std::string().find(std::string()) == string::npos); // WRONG!!! (non-standard)
    

    This is especially bad if you try to write portable code because it's so hard to prove that no feature depends on that behaviour. Sadly in my case that's actually true: it does string processing to shorten phone numbers input depending on a subscriber line spec.

    On Cppreference, I see in std::basic_string::find an explicit description about empty strings that I think matches exactly the case in question:

    an empty substring is found at pos if and only if pos <= size()

    The referred pos defines the position where to start the search, it defaults to 0 (the beginning).

    A standard-compliant C++ Standard Library will pass the following tests:

    TEST_ASSERT(std::string().find(std::string()) == 0);
    TEST_ASSERT(std::string().substr(0, 0).empty());
    TEST_ASSERT(std::string().substr().empty());
    

    This interpretation of "contain" answers the question with yes.

提交回复
热议问题