training

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

strcomp.c (929B)


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