2017-04-03 78 views
2

我想在另一個字符串中找到給定的字符串。以前的計算已知可能的開始採購。例如:子串與std :: memcmp或string :: compare比較?

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

都相同呢?如果關鍵字長度超過了從起始位置開始的輸入長度,與memcmp的比較仍然是正確的。 strncmp是更安全的方法嗎?

+0

爲什麼不使用std :: string提供的find()方法? –

+0

@Oz。性能。那時我已經知道可能的關鍵字的位置和長度。使用find()我必須爲整個輸入字符串上的每個關鍵字調用find。輸入字符串可能根本沒有關鍵字。 – aggsol

回答

4

這是安全的,多餘的,因爲std::char_traits<char>::compare反正使用memcmp在大多數標準庫供應商(我檢查VC++和GCC,它分別使用memcmp__builtin_memcmp)。

以表現 - 它不會有太大的改變。

更好地堅持到std::string::compare

1

你可以使用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"; 

真虛假

live wandbox example

+0

我喜歡使用新的C++ 17功能。不應該substr()已經照顧過流的可能性?子字符串會更短並且不匹配。另一方面,substr()總是創建一個副本。我必須先測試它。 – aggsol

+0

['substr'](http://en.cppreference.com/w/cpp/string/basic_string_view/substr)創建一個新的'string_view' - 應該很便宜。如果值超出範圍,它也會拋出,這就是爲什麼我明確檢查它。 –

+0

此外,我只是更新了使用'compare'的答案:) –