Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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 154 views
2 answers 252 views
1 answer 112 views
112 views asked Dec 16, 2022 by avibootz
1 answer 235 views
1 answer 109 views
109 views asked Aug 23, 2024 by avibootz
1 answer 113 views
...