简体   繁体   中英

Substring comparision with std::memcmp or string::compare?

I want to find a given string within another string. Possible start poisition in known by previous calculations. Example:

int main()
{
    std::string input("Foo Bar Hash Bang");
    std::string keyword("Bar");

    const char* inputStart = input.c_str() + 4; // at 'B'
    std::cout << "memcmp=" << std::memcmp(inputStart, keyword.c_str(), keyword.length()) << "\n";

    std::cout << "compare=" << input.compare(4, keyword.length(), keyword) << "\n";

    return 0;
}

Ideone

Are both equivalent? If the keyword length would exceed the input length from the start position the comparision with memcmp would be still correct. Is strncmp the safer approach?

It is safe, and redundant, as std::char_traits<char>::compare anyway uses memcmp on most of the standard library vendors (I checked VC++ and GCC, which uses memcmp and __builtin_memcmp respectively) .

so as for performance - it won't change much.

better stick to std::string::compare .

You could use std::string_view :

bool matchSubstring(std::string_view haystack, 
                    std::string_view needle, 
                    std::size_t pos)
{
    if(haystack.size() < pos + needle.size()) return false;
    return haystack.compare(pos, needle.size(), needle) == 0;
}

Usage:

std::string input("Foo Bar Hash Bang");
std::string keyword("Bar");

std::cout << std::boolalpha << matchSubstring(input, keyword, 4) << "\n"
                            << matchSubstring(input, keyword, 5) << "\n"
                            << matchSubstring(input, keyword, 1000) << "\n";

true false false

live wandbox example

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