7

使用 C,我需要在可能包含空值的缓冲区中找到一个子字符串。

haystack = "Some text\0\0\0\0 that has embedded nulls".
needle   = "has embedded"r 

我需要返回子字符串的开头,或 null,类似于 strstr():

request_segment_end = mystrstr(request_segment_start, boundary);

您是否知道任何现有的实现?

更新

我在谷歌的代码搜索中找到了 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;
}
4

2 回答 2

8

如果你在一个有 memmem 的系统上,你可以使用 memmem,比如 linux(它是一个 GNU 扩展)。就像 strstr 一样,但适用于字节并且需要两个“字符串”的长度,因为它不检查以空结尾的字符串。

#include <string.h>

void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen);
于 2011-03-15T08:12:02.653 回答
6

“字符串”包含空字符对我来说没有意义。字符串以空值结尾,因此第一次出现标志着字符串的结尾。此外,什么是单词后面的空终止符后面"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);
于 2011-03-15T08:19:21.850 回答