簡體   English   中英

strcasestr仍然無法正常工作

[英]strcasestr still not working

所以我通讀了其他問題,他們被告知在任何包含之前放#define _GNU_SOURCE它會起作用,但它對我不起作用。 我也嘗試添加#define _GNU_SOURCE char *strcasestr(const char *haystack, const char *needle); 但仍然無法正常工作。 我找不到任何其他相關信息,也許任何人都可以提供幫助? 提前致謝。

錯誤:函數'strcasestr'的隱式聲明

/**
 *
 * Description:  This is code for Lab 3 Task 2.
 *               Reads data from file and gives opportunity to search by cities
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    printf("Please input the city you want to find employees in:");
    scanf("%s", input);
    maxline = i;
    for (i = 0; i <= maxline; i++) {
        if (strcasestr(employee[i].city, input) != 0) { // PROBLEM
            printf("%d %s %s %s\n", &employee[i].ID, employee[i].fn,
                                    employee[i].ln, employee[i].city);
            amount++;
        }
    }
    printf("%d matches out of %d members", amount, maxline);
    return 0;
}

strcasestr函數不可用作標准Windows構建環境的一部分。 它不是C標准庫的一部分,只與某些平台和構建環境一起發布。

但是,您可以編寫自己的版本。 這是一個基於天真字符串匹配算法的簡單方法。 您可以使用Rabin-Karp,Boyer-Moore或Knuth-Morris-Pratt算法做得更好:

char* myStrcasestr(const char* haystack, const char* needle) {
    /* Edge case: The empty string is a substring of everything. */
    if (!needle[0]) return (char*) haystack;

    /* Loop over all possible start positions. */
    for (size_t i = 0; haystack[i]; i++) {
        bool matches = true;
        /* See if the string matches here. */
        for (size_t j = 0; needle[j]; j++) {
            /* If we're out of room in the haystack, give up. */
            if (!haystack[i + j]) return NULL;

            /* If there's a character mismatch, the needle doesn't fit here. */
            if (tolower((unsigned char)needle[j]) != 
                tolower((unsigned char)haystack[i + j])) {
                matches = false;
                break;
            }
        }
        if (matches) return (char *)(haystack + i);
    }
    return NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM