子字符串与 std::memcmp 或字符串::比较的比较

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

本文关键字:字符串 比较 std memcmp      更新时间:2023-10-16

我想在另一个字符串中找到给定的字符串。通过先前的计算已知可能的起始位置。例:

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;
}

艾德酮

两者等效吗?如果关键字长度超过起始位置的输入长度,则与memcmp的比较仍然是正确的。strncmp更安全的方法吗?

它是

安全的,也是冗余的,因为无论如何std::char_traits<char>::compare大多数标准库供应商都使用memcmp(我检查了VC++和GCC,它们分别使用memcmp__builtin_memcmp(。

至于性能 - 它不会有太大变化。

最好坚持std::string::compare.

您可以使用

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;
}

用法:

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";

真 假 假

活魔杖盒示例