使用C,我需要在缓冲区内找到一个可能包含空值的子字符串.
haystack = "Some text\0\0\0\0 that has embedded nulls".
needle = "has embedded"r
Run Code Online (Sandbox Code Playgroud)
我需要返回子串的开头,或者null,similat到strstr():
request_segment_end = mystrstr(request_segment_start, boundary);
Run Code Online (Sandbox Code Playgroud)
您知道的是否存在任何现有实施?
更新
我在google的codesearch上找到了memove的实现,我在这里逐字复制,未经测试,
/*
* memmem.c
*
* Find a byte string inside a longer byte string
*
* This uses the "Not So Naive" algorithm, a very simple but
* usually effective algorithm, see:
*
* http://www-igm.univ-mlv.fr/~lecroq/string/
*/
#include <string.h>
void *memmem(const void *haystack, size_t n, const void *needle, size_t m)
{
const unsigned char *y = (const unsigned char *)haystack;
const unsigned char *x = (const unsigned char *)needle;
size_t j, k, l;
if (m > n || !m || !n)
return NULL;
if (1 != m) {
if (x[0] == x[1]) {
k = 2;
l = 1;
} else {
k = 1;
l = 2;
}
j = 0;
while (j <= n - m) {
if (x[1] != y[j + 1]) {
j += k;
} else {
if (!memcmp(x + 2, y + j + 2, m - 2)
&& x[0] == y[j])
return (void *)&y[j];
j += l;
}
}
} else
do {
if (*y == *x)
return (void *)y;
y++;
} while (--n);
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
如果你在拥有它的系统上,你可以使用memmem,比如linux(它是一个GNU扩展).就像strstr一样,但是在字节上工作并且需要两个"字符串"的长度,因为它不检查空终止字符串.
#include <string.h>
void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen);
Run Code Online (Sandbox Code Playgroud)
对我来说,“字符串”包含空字符是没有意义的。字符串以空值结尾,因此第一次出现会标记字符串的结尾。另外,该单词后面的空终止符后面"nulls"没有任何字符了。
如果您打算在缓冲区中搜索,那对我来说更有意义。您只需要搜索缓冲区而忽略空字符,而只依赖于长度。我不知道任何现有的实现,但是应该很容易就能实现一个简单的天真的实现。当然,根据需要在这里使用更好的搜索算法。
char *search_buffer(char *haystack, size_t haystacklen, char *needle, size_t needlelen)
{ /* warning: O(n^2) */
int searchlen = haystacklen - needlelen + 1;
for ( ; searchlen-- > 0; haystack++)
if (!memcmp(haystack, needle, needlelen))
return haystack;
return NULL;
}
char haystack[] = "Some text\0\0\0\0 that has embedded nulls";
size_t haylen = sizeof(haystack)-1; /* exclude null terminator from length */
char needle[] = "has embedded";
size_t needlen = sizeof(needle)-1; /* exclude null terminator from length */
char *res = search_buffer(haystack, haylen, needle, needlen);
Run Code Online (Sandbox Code Playgroud)