training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

mystrcomp.c (1198B)


      1 /* Exercise 8.30 */
      2 
      3 /* WRONG!! WRONG!! WRONG!! */
      4 
      5 #include <stdio.h>
      6 
      7 int strcmp(const char *s1, const char *s2);
      8 int strncmp(const char *s1, const char *s2, size_t n);
      9 
     10 int main(void)
     11 {
     12    char string1[] = "abcdef";
     13    char string2[] = "abcdea";
     14 
     15    printf("strcmp() = %d\n", strcmp(string1, string2) );
     16    printf("strncmp() = %d\n", strncmp(string1, string2, 4) ); 
     17 
     18    return 0;
     19 } /* E0F main */
     20 
     21 /* Compare two strings */
     22 int strcmp(const char *s1, const char *s2)
     23 {
     24    int i;
     25    long n1 = 0, n2 = 0;
     26 
     27    for(i = 0; s1[i] != '\0'; i++)
     28       n1 += s1[i];
     29 
     30    for(i = 0; s2[i] != '\0'; i++)
     31       n2 += s2[i];
     32 
     33    /* Second version
     34    for(i = 0; *(s1 + i) != '\0'; i++)
     35       n1 += *(s1 + i);
     36 
     37    for(i = 0; *(s2 + i) != '\0'; i++)
     38       n2 += *(s2 + i);
     39    */
     40 
     41    return n1 - n2;
     42 
     43 } /* eof strcmp() */
     44 
     45 /* Compare n characters of two strings */
     46 int strncmp(const char *s1, const char *s2, size_t n)
     47 {
     48    int i;
     49    long n1 = 0, n2 = 0;
     50 
     51    for(i = 0; i < (int)n; i++) {
     52       if( s1[i] == '\0' )
     53 	 break;
     54 
     55       n1 += s1[i];
     56       n2 += s2[i];
     57 
     58       /* Second version
     59       if( *(s1 + i) == '\0' )
     60 	 break;
     61 
     62       n1 += *(s1 + i);
     63       n2 += *(s2 + i);
     64       */
     65    }
     66 
     67    return n1 - n2;
     68 
     69 }
     70