w3resource

C programming: Example of C custom strcmp() function

Implementing a custom strcmp() function in C.

The strcmp() function is used to compare two given strings.

Return value from strcmp()

Name Value
string1 is less than string2 < 0
string1 is identical to string2 0
string1 is greater than string2 >0

Here is an implementation of a custom strcmp() function in C language.

Code:

#include <stdio.h>

int my_strcmp(char *str1, char *str2) {
    int i = 0;
    while(str1[i] == str2[i]) {
        if(str1[i] == '\0' || str2[i] == '\0') {
            break;
        }
        i++;
    }
    if(str1[i] == '\0' && str2[i] == '\0') {
        return 0;
    }
    else {
        return str1[i] - str2[i];
    }
}

int main() {
char str1[] = "1234567890";
   char str2[] = "1234567890";
   int result;
   printf("Original text:");
   printf("\n%s",str1);
   printf("\n%s",str2);
   printf( "\nCompare the said two strings:");
   result = my_strcmp(str1, str2);
   if( result < 0 )
      printf( "\nFirst is less than second.\n" );
   else if( result == 0 )
      printf( "\nFirst is equal to second.\n" );
   else
      printf( "\nFirst is greater than second.\n" );
   char str3[] = "12345678901";
   char str4[] = "12345678900";
   printf("\nOriginal text:");
   printf("\n%s",str3);
   printf("\n%s",str4);
   printf( "\nCompare the said two strings:");
   result = my_strcmp(str3, str4);
   if( result < 0 )
      printf( "\nFirst is less than second.\n");
   else if( result == 0 )
      printf( "\nFirst is equal to second.\n");
   else
      printf( "\nFirst is greater than second.\n");   
      
   char str5[] = "12345678901100345678";
   char str6[] = "12345678901297650033";   
   printf("\nOriginal text:");
   printf("\n%s",str5);
   printf("\n%s",str6);
   result = my_strcmp(str5, str6);
   if( result < 0 )
      printf( "\nFirst is less than second.\n");
   else if( result == 0 )
      printf( "\nFirst is equal to second.\n");
   else
      printf( "\nFirst is greater than second.\n");   
    return 0;
}

Output:

Original text:
1234567890
1234567890
Compare the said two strings:
First is equal to second.

Original text:
12345678901
12345678900
Compare the said two strings:
First is greater than second.

Original text:
12345678901100345678
12345678901297650033
First is less than second.

The above function works by iterating over the characters in the two strings "str1" and "str2", comparing them one by one. If the characters match, it continues to the next pair of characters. If one of the strings ends before the other, the function breaks out of the loop and checks if both strings have ended. If they have, it returns 0 (indicating the strings are equal); otherwise, it returns the difference between their ASCII values.



Follow us on Facebook and Twitter for latest update.