Case Insensitive String comp in C

前端 未结 11 1115
天涯浪人
天涯浪人 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:16

    I would use stricmp(). It compares two strings without regard to case.

    Note that, in some cases, converting the string to lower case can be faster.

    0 讨论(0)
  • 2020-11-27 04:16
    int strcmpInsensitive(char* a, char* b)
    {
        return strcmp(lowerCaseWord(a), lowerCaseWord(b));
    }
    
    char* lowerCaseWord(char* a)
    {
        char *b=new char[strlen(a)];
        for (int i = 0; i < strlen(a); i++)
        {
            b[i] = tolower(a[i]);   
        }
        return b;
    }
    

    good luck

    Edit-lowerCaseWord function get a char* variable with, and return the lower case value of this char*. For example "AbCdE" for value of char*, will return "abcde".

    Basically what it does is to take the two char* variables, after being transferred to lower case, and make use the strcmp function on them.

    For example- if we call the strcmpInsensitive function for values of "AbCdE", and "ABCDE", it will first return both values in lower case ("abcde"), and then do strcmp function on them.

    0 讨论(0)
  • 2020-11-27 04:20

    There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp in the header strings.h; Microsoft systems have stricmp. To be on the portable side, write your own:

    int strcicmp(char const *a, char const *b)
    {
        for (;; a++, b++) {
            int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);
            if (d != 0 || !*a)
                return d;
        }
    }
    

    But note that none of these solutions will work with UTF-8 strings, only ASCII ones.

    0 讨论(0)
  • 2020-11-27 04:20

    Take a look to strcasecmp() in strings.h.

    0 讨论(0)
  • 2020-11-27 04:20
    static int ignoreCaseComp (const char *str1, const char *str2, int length)
    {
        int k;
        for (k = 0; k < length; k++)
        {
    
            if ((str1[k] | 32) != (str2[k] | 32))
                break;
        }
    
        if (k != length)
            return 1;
        return 0;
    }
    

    Reference

    0 讨论(0)
提交回复
热议问题