Case Insensitive String comp in C

前端 未结 11 1169
天涯浪人
天涯浪人 2020-11-27 03:45

I have two postcodes char* that I want to compare, ignoring case. Is there a function to do this?

Or do I have to loop through each use the tolower func

11条回答
  •  一生所求
    2020-11-27 04:06

    I've found built-in such method named from which contains additional string functions to the standard header .

    Here's the relevant signatures :

    int  strcasecmp(const char *, const char *);
    int  strncasecmp(const char *, const char *, size_t);
    

    I also found it's synonym in xnu kernel (osfmk/device/subrs.c) and it's implemented in the following code, so you wouldn't expect to have any change of behavior in number compared to the original strcmp function.

    tolower(unsigned char ch) {
        if (ch >= 'A' && ch <= 'Z')
            ch = 'a' + (ch - 'A');
        return ch;
     }
    
    int strcasecmp(const char *s1, const char *s2) {
        const unsigned char *us1 = (const u_char *)s1,
                            *us2 = (const u_char *)s2;
    
        while (tolower(*us1) == tolower(*us2++))
            if (*us1++ == '\0')
                return (0);
        return (tolower(*us1) - tolower(*--us2));
    }
    

提交回复
热议问题