DOC: stricmp() Compares Using Lowercase Characters

ID: Q71977

6.00 6.00a 6.00ax | 6.00 6.00a | 1.00 1.50

MS-DOS            | OS/2       | WINDOWS
kbprg kbdocerr

The information in this article applies to:

SUMMARY

The Microsoft C run-time library contains a function called stricmp() that does case-insensitive comparisons of null-terminated strings. When comparing strings, stricmp() converts any letters that are uppercase to lowercase letters for the sake of comparison. In most cases, this case conversion is unimportant but occasionally it may result in unexpected behavior.

MORE INFORMATION

To illustrate when case conversion by stricmp() affects the outcome of a comparison, assume that you have the two strings "JOHNSTON" and "JOHN_HENRY". The string "JOHN_HENRY" will be considered less than "JOHNSTON" because the "_" has a lower ASCII value than a lowercase "S".

In fact, any character that has an ASCII value between 91 and 96 will be considered less than any letter. The following are the characters in this range of ASCII values:

   [  \  ]  ^  _  `

If the strcmp() function is used instead of stricmp(), "JOHN_HENRY" will be greater than "JOHNSTON".

The above behavior of the stricmp() function is correct. However, the documentation that ships with the products listed above fail to mention that the strings are first converted to lowercase letters. The Microsoft C Compiler "Run-Time Library Reference" manuals for C version 5.1 and C/C++ 7.0 do mention this conversion.

If you require strings to be compared as uppercase letters, the sample code below illustrates one way to do so. With this function, "JOHN_HENRY" will be greater than "JOHNSTON".

NOTE: There is also a function called strcmpi(), but this name is an obsolete synonym for stricmp(). All information here pertaining to stricmp() also pertains to strcmpi().

Sample Code

int stricmp_alt(char * string1, char * string2)
{
   int first,second;

   do {
      first  = toupper(*string1);
      second = toupper(*string2);
      string1++;
      string2++;
   } while (first && first == second);

   return(first - second);
}

Additional reference words: 5.10 6.00 6.00a 6.00ax 1.00 1.50 KBCategory: kbprg kbdocerr KBSubcategory: CRTIss Keywords : kb16bitonly

Last Reviewed: November 12, 1998