9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex09_modular.c (1005B)
   1 /*  Makes a lexicographical comparison between the first n    */
   2 /*    numbers of two given strings                            */
   3 /*    similar to strncmp() function from <string.h>            */
   4 
   5 #include <stdio.h>
   6 #include <string.h>
   7 
   8 /*    This function calculates the length of given string
   9     and returns it by its name, equivalent to strlen()        
  10     function from <string.h> library                        */
  11 size_t str_len(const char *str)
  12 {
  13     size_t i;
  14 
  15     if(!str) return 1;
  16 
  17     for(i = 0; str[i]; i++);
  18 
  19     return i;
  20 }
  21 
  22 /*  This function is equivalent to strncmp() function from   
  23     <string.h> library                                      */
  24 int str_cmp(const char *sa, const char *sb, size_t n)
  25 { 
  26     /*    Since the return value is an integer this function won't check for errors    */
  27     int cmp;
  28     size_t i;
  29 
  30     for(i = cmp = 0; (i < n) && sa[i] && sb[i]; i++)
  31         cmp += sa[i] - sb[i];
  32 
  33     return cmp;
  34 }
  35 
  36     
  37 int main(void) {
  38 
  39     char s1[] = "HELLO";
  40     char s2[] = "hello";
  41 
  42     int i, j;
  43     i = str_cmp(s1, s2, 109);
  44     j = strncmp(s1, s2, 8);
  45 
  46     printf("%d\n%d\n", i, j);
  47     return 0;
  48 }