是否有一個STL算法可以用來像memmem()那樣在緩衝區內搜索字節序列?memmem()STL方式?
回答
我不知道這是否是好的代碼,但是下面的作品,使用std::search
:
#include <cstdio>
#include <string.h>
#include <algorithm>
int main(int argc, char **argv)
{
char *a = argv[0];
char *a_end = a + strlen(a);
char *match = "out";
char *match_end = match+strlen(match); // If match contained nulls, you would have to know its length.
char *res = std::search(a, a_end, match, match_end);
printf("%p %p %p\n", a, a_end, res);
return 0;
}
爲什麼不使用strstr?
沒有執行算法。你可以實現你自己的謂詞與std :: find_if結合使用,但它是過度工程,IMO。
'strstr'將要求您零終止序列,並且如果它們可以包含零將不起作用。有一個算法:'std :: search'。 – 2010-07-19 11:35:17
你是對的。我忘了它... – 2010-07-19 11:42:40
std::search
將在另一個序列內發現一個序列的首次出現。
什麼find
和substr
?
#include <string>
using std::string;
...
size_t found;
found = s.find("ab",4);
if (found != string::npos)
finalString = s.substr(found); // get from "ab" to the end
如果二進制字符串包含null字節,它失敗。 – Raindog 2011-02-28 21:06:42
舊版本做了sizeof(匹配),它只工作,因爲匹配指向一個3字母字符串,並且它在32位體系結構上進行了測試。 strlen(match)是獲取該字符串長度的正確方法。另一種方法是使用char match [] =「out」,然後使用sizeof(match)。 – boatcoder 2012-12-29 00:14:02
爲了提高效率,您可能需要使用Boyer-Moore-Horspool:http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm – boatcoder 2012-12-29 00:16:33