SiteBanner

If it were only so easy to code "if (string1 < string2)" in 'C'...  Such is not the case.  We look here at one of the handful of string comparison/investigation functions.

 

 l Function 'strcmp()' returns:
  • Negative number if left-value appears before right-value in lexicographical order
  • Zero if left-value and right-value compare equal
  • Positive number if left-value appears after right-value in lexicographical order
 

 

(right-click to download)

/* pgm17 source */

#include <stdio.h>
#include <string.h>

#define ITEMS 11

int main(void) {
     char *words1[ITEMS] = {"A", "bird", "Sea", "came", "O", "down", "the", "walk", "11", "Foo", "Bang"};
     char *words2[ITEMS] = {"A", "boy", "Tea", "could", "E", "dive", "them", "walls", "11", "Faa", "Bing"};
     int s_cmp;
     int j;

     printf("\nSTRCMP() does string comparisons & also makes sandwiches.\n\n");

     for (j = 0; j < ITEMS; j++) {
          s_cmp = strcmp(words1[j], words2[j]);
          if (s_cmp < 0)           printf("%-8s is less than        %s\n", words1[j], words2[j]);
         else if (s_cmp == 0)  printf("%-8s is equal to         %s\n", words1[j], words2[j]);
         else                           printf("%-8s is greater than     %s\n", words1[j], words2[j]);
         }

     printf("\n('A'=65 decimal, 'B'=66, 'y'=121, 'z'=122)\n\n");
     for (j = 'A'; j <= 'z'; j++) {
          if ((j > 'Z') && (j < 'a'))    // there are some punctuation chars between CAPS and lowercase
               continue;                  // don't print them by continuing back to top of LOOP

          printf("%c", j);
          }

     printf("\n\n");
     return(0);
     }