How to implement my own strcmp() function to compare two strings in C

2 Answers

0 votes
#include <stdio.h>
   
int my_strcmp(char *s, char *t);
  
int main(void)
{
    char s1[13] = "abc", s2[13] = "Abc";   
    int rv;
 
    rv = my_strcmp(s1, s2);
 
    if (rv < 0)
        printf("s1 is less than s2");
    else if (rv > 0) 
             printf("s2 is less than s1"); // s2 is less than s1 'a' = 97 'A' = 65
         else
             printf("s1 is equal to s2");
    
    return 0;
}
  
int my_strcmp(char *s, char *t) 
{ 
    int i; 
    
    for (i = 0; s[i] == t[i]; i++) 
         if (s[i] == '\0') 
             return 0; 
    
    return s[i] - t[i]; 
} 
  
  
/*
run:
     
s2 is less than s1
 
*/

 



answered Nov 20, 2015 by avibootz
0 votes
#include <stdio.h>
   
int my_strcmp(char *s1, char *s2);
  
int main(void)
{
    char s1[13] = "abc", s2[13] = "Abc";   
    int rv;
 
    rv = my_strcmp(s1, s2);
 
    if (rv < 0)
        printf("s1 is less than s2");
    else if (rv > 0) 
             printf("s2 is less than s1"); // s2 is less than s1 'a' = 97 'A' = 65
         else
             printf("s1 is equal to s2");
    
    return 0;
}
  
int my_strcmp(char *s1, char *s2) 
{ 
    for ( ; *s1 == *s2; s1++, s2++) 
         if (*s1 == '\0') 
             return 0; 
             
    return *s1 - *s2; 
} 
  
  
/*
run:
     
s2 is less than s1
 
*/

 



answered Nov 20, 2015 by avibootz

Related questions

1 answer 180 views
2 answers 286 views
1 answer 133 views
133 views asked Dec 16, 2022 by avibootz
1 answer 260 views
1 answer 144 views
144 views asked Aug 23, 2024 by avibootz
1 answer 139 views
...