本文介绍了实施strnstr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图在C中实现一个strnstr函数(strstr,但它检查长度),由于某种原因它不起作用(输出始终为no):
I am trying to implement a strnstr function into C (strstr but it checks the length), for some reason it doesn't work (output is always no):
#include <stdio.h>
char *searchingFor = "stackdummy";
char *in = "la da\ndoo a da\nnow here comes the stack\nok there it was.\n";
char *strnstr(char *s1, char *s2, int length) {
if(s1 == NULL || s2 == NULL) return NULL;
printf("searching \n\n\"%s\"\n for %.*s\n", s1, length, s2);
char *ss1 = malloc(strlen(s1) + 1);
strcpy(ss1, s1);
char *ss2 = malloc(length + 1);
strncpy(ss2, s2, length);
char *result = strstr(ss1, ss2);
free(ss1);
free(ss2);
return result;
}
int main(void) {
printf("found: %s\n", strnstr(in, searchingFor, 5) ? "yes" : "no");
printf("found: %s\n", strnstr(in, searchingFor, 5) ? "yes" : "no");
printf("found: %s\n", strnstr(in, searchingFor, 5) ? "yes" : "no");
return 0;
}
推荐答案
Chris Dodd 提供的实现具有有以下缺点:
The implementation provided by Chris Dodd has the following disadvantages:
- 它违反了
strnstr
的目的,因为while
条件使用了无界字符串函数strchr
- 这取决于
haystack
被NULL终止,这与strnstr
的常规实现有所不同,例如, GNU-达尔文 - 当未内联
strchar
时,对strchr
的调用是不必要的函数调用 - 当
len
为零时,返回haystack
而不是NULL
,这与公认的strstr
语义有所偏离 - 当
needle
的长度为零时,返回一个空字符串而不是haystack
- It defeats the purpose of
strnstr
in that thewhile
condition uses the unbounded string functionstrchr
- It depends on
haystack
being NULL terminated, which is a deviation from the usual implementation ofstrnstr
, for example as provided by GNU-Darwin - The call to
strchr
is an unnecessary function call whenstrchar
is not inlined - Returns
haystack
instead ofNULL
whenlen
is zero, a deviation from the acceptedstrstr
semantics - Returns an empty string instead of
haystack
whenneedle
has length of zero
以下实现可以解决上述问题,而不会像GNU-Darwin实现那样难以理解,并且已获得知识共享许可:
The following implementation remedies the above problems without becoming as difficult to read as the GNU-Darwin implementation, and is Creative Commons licensed:
#include <string.h>
char *strnstr(const char *haystack, const char *needle, size_t len)
{
int i;
size_t needle_len;
if (0 == (needle_len = strnlen(needle, len)))
return (char *)haystack;
for (i=0; i<=(int)(len-needle_len); i++)
{
if ((haystack[0] == needle[0]) &&
(0 == strncmp(haystack, needle, needle_len)))
return (char *)haystack;
haystack++;
}
return NULL;
}
这篇关于实施strnstr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!