- 论坛徽章:
- 95
|
回复 1# snowboy9859
我自己寫了個:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char *my_strstr(const char *haystack, const char *needle);
- void report_bug(const char *a, const char *b, const char *c);
- void report_status(const char *a, const char *b, const char *c);
- #define ARRAYLEN(a) (sizeof(a)/sizeof(a[0]))
- int
- main(void)
- {
- int found_bug, verbose;
- /* FIXME: add option to set verbose */
- verbose = 1;
- struct {
- char *a, *b;
- } testcase[] = {
- { NULL, NULL },
- { NULL, "abc" },
- { "abc", NULL },
- { "abc", "ab" },
- { "abc", "bc" },
- { "ab", "abc" },
- { "aaabc", "aabc" }
- };
- found_bug = EXIT_SUCCESS;
- for (unsigned int i = 0; i < ARRAYLEN(testcase); i++) {
- char *a, *b, *c1, *c2;
- a = testcase[i].a;
- b = testcase[i].b;
- c1 = my_strstr(a, b);
- /* strstr doesn't allow empty a or b. */
- if (a == NULL || b == NULL) {
- if (c1 != NULL) {
- report_bug(a, b, c1);
- found_bug = EXIT_FAILURE;
- }
- if (verbose)
- report_status(a, b, c1);
- continue;
- }
- c2 = strstr(a, b);
- if (c2 == NULL) {
- if (c1 != c2) {
- report_bug(a, b, c1);
- found_bug = EXIT_FAILURE;
- }
- }
- else {
- if (strcmp(c1, c2) != 0) {
- report_bug(a, b, c1);
- found_bug = EXIT_FAILURE;
- }
- }
- if (verbose)
- report_status(a, b, c1);
- }
- exit(found_bug);
- }
- char *
- my_strstr(const char *haystack, const char *needle)
- {
- int i, j, pos;
- if (haystack == NULL || needle == NULL) {
- return NULL;
- }
- pos = -1;
- while (1) {
- for (i = pos + 1; haystack[i] != needle[0]; i++)
- ;
- pos = i++;
- for (j = 1; haystack[i] && needle[j] && haystack[i] == needle[j]; i++, j++)
- ;
- if (needle[j] == '\0')
- return (char *)(haystack + pos);
- else {
- /* HAYSTACK is exhausted. */
- if (haystack[i] == '\0')
- return NULL;
- }
- }
- }
- void
- report(const char *s, const char *a, const char *b, const char *c)
- {
- a = a ? a : "NULL";
- b = b ? b : "NULL";
- c = c ? c : "NULL";
- fprintf(stderr, "%s: a = %s, b = %s, c = %s\n", s, a, b, c);
- }
- void
- report_bug(const char *a, const char *b, const char*c)
- {
- report("BUG", a, b, c);
- }
- void
- report_status(const char *a, const char *b, const char*c)
- {
- report("SUCCESS", a, b, c);
- }
复制代码 測試:
- lee@debian:~/code-fragment/2011/08$ gcc -std=gnu99 strstr.c -o /tmp/ss
- lee@debian:~/code-fragment/2011/08$ /tmp/ss
- SUCCESS: a = NULL, b = NULL, c = NULL
- SUCCESS: a = NULL, b = abc, c = NULL
- SUCCESS: a = abc, b = NULL, c = NULL
- SUCCESS: a = abc, b = ab, c = abc
- SUCCESS: a = abc, b = bc, c = bc
- SUCCESS: a = ab, b = abc, c = NULL
- SUCCESS: a = aaabc, b = aabc, c = aabc
复制代码 |
|