Thread: Question about strcmp()

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    31

    Question about strcmp()

    Theres an example on tutorialspoint.com that goes like this:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
       char str1[15];
       char str2[15];
       int ret;
    
    
       strcpy(str1, "abcdef");
       strcpy(str2, "ABCDEF");
    
       ret = strcmp(str1, str2);
    
       if(ret < 0)
       {
          printf("str1 is less than str2");
       }
       else if(ret > 0) 
       {
          printf("str2 is less than str1");
       }
       else 
       {
          printf("str1 is equal to str2");
       }
       
       return(0);
    }

    Why is the answer to this example: "str2 is less than str1"

    When both strings are the same and only difference is one is uppercase. How does strcmp work here?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    strcmp works on ANSI strings... so uppercase comes before lower case like in this table.

  3. #3
    Registered User
    Join Date
    May 2016
    Posts
    31
    Ah, ok that makes sense. Thank you.

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Windows has stricmp for case-insensitive compare (although they say it's deprecated in favour of _stricmp).
    *nix has strcasecmp.
    What exactly is upper or lower case depends on the locale.

    You could of course write your own where you compare letters one by one applying toupper (or tolower) to each.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp question
    By alphasil in forum C Programming
    Replies: 6
    Last Post: 07-16-2012, 03:30 AM
  2. strcmp question
    By lowestOne in forum C Programming
    Replies: 32
    Last Post: 06-09-2012, 04:00 PM
  3. strcmp question
    By voidpain() in forum C Programming
    Replies: 5
    Last Post: 08-11-2011, 09:16 PM
  4. question about strcmp
    By lolguy in forum C Programming
    Replies: 3
    Last Post: 03-07-2009, 10:39 PM
  5. A question about strcmp...
    By krsauls in forum C Programming
    Replies: 6
    Last Post: 05-02-2007, 04:39 AM

Tags for this Thread