9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex08_modular.c (1309B)
   1 /*    Makes a lexicographical comparison between two strings    */
   2 /*    similar to strcmp() function from <string.h>        */
   3 
   4 #include <stdio.h>
   5 
   6 /*    This function calculates the length of given string
   7     and returns the lenghth by its name as a size_t        */
   8 size_t str_len(const char *str) 
   9 {
  10     if(str == NULL)
  11         return 1;
  12 
  13     size_t i;
  14     while(str[i++])
  15         ;
  16 
  17     return i;
  18 }
  19 
  20 /*    This function is equivalent to strcmp() function from    
  21     <string.h> library                    */
  22 int str_cmp(const char *str1, const char *str2) 
  23 { 
  24     /* In case one of the given strings is NULL returns 1; */ 
  25     if(str1 == NULL || str2 == NULL)
  26         return 1;
  27 
  28 
  29     char aux1, aux2;
  30     int i, j, cmp, str1_len, str2_len;
  31     str1_len = str_len(str1);
  32     str2_len = str_len(str2);
  33 
  34     /* Assigns the length of the longer string to j; */
  35     j = (str1_len > str2_len) ? str1_len : str2_len; 
  36 
  37     /* The for loop itinirate until the longest str ENDs */
  38     for(i = 0, cmp = 0; i < j; i++) {
  39 
  40         aux1 = str1[i];
  41         aux2 = str2[i];
  42 
  43         /* This statement assigns to cmp the difference between */
  44         /* the two coresponding chars of str1 and str2 */
  45         if(aux1 < aux2) {
  46             cmp -= (aux2 - aux1);
  47         } else if (aux1 > aux2) {
  48                 cmp += (aux1 - aux2);
  49             }
  50 
  51     }
  52     return cmp;
  53 }
  54 
  55     
  56 int main(void) {
  57 
  58     char s1[] = "AB";
  59     char s2[] = "ABC";
  60 
  61     int i, j;
  62     i = str_cmp(s1, s2);
  63 
  64     printf("%d\n", i);
  65     
  66     return 0;
  67 }