簡體   English   中英

如何使用 strstr 但通過 C 中的字母來檢測單詞

[英]How to detect a word using strstr but by alphabets in C

您好,我從 string.h 中得到了這個 function,我用它作為指針來檢測單詞的存在

p = strstr(string, "WORD");

然后在同一個代碼中我留下了另一行

  p = strstr(chaine, "word");

為了檢測大寫和小寫的單詞。 但問題是,我意識到用戶可以輸入 Word 或 WoRD 或 Word 等,因此該行不會檢測到它。 基本上如何使用那個 function 來寫字的所有情況。 如果這不可能,string.h 中是否還有其他函數可以幫助檢測到這一點?

mystrstr 是一個標准實現。

int strneq(const char *str1, const char *str2, size_t len)
{
    int result = 0;
    while(*str2 && len--)
    {
        if(toupper((unsigned char)*str1) != toupper((unsigned char)*str2))
        {
            result = 1;
            break;
        }
        str1++;
        str2++;
    }
    return result;
}

char *mystrstr(const char *s, const char *find)
{
    char c, sc;
    size_t len;
    if ((c = *find++) != 0) {
        len = strlen(find);
        do {
            do {
                if ((sc = *s++) == 0)
                    return (NULL);
            } while (sc != c);
        } while (strneq(s, find, len) != 0);
        s--;
    }
    return ((char *)s);
}

或者

char *mystrstr(const char *s, const char *find)
{
    char *str = strdup(s), *wrk = NULL, *findu = strdup(find);
    if(str && findu)
    {
        wrk = str;
        while((*wrk = toupper((unsigned char)*wrk))) wrk++;
        wrk = findu;
        while((*wrk = toupper((unsigned char)*wrk))) wrk++;
        wrk = strstr(str, findu);
    }
    free(str);
    free(findu);
    return wrk;
}

暫無
暫無

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

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