Implement strcmp() function in C
Write an efficient function to implement strcmp() function in C. The standard strcmp() function compares the two strings and returns an integer indicating the relationship between them.
The prototype of the strcmp() is:
int strcmp(const char* X, const char* Y);
The strcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by X is greater than, equal to, or less than the string pointed to by Y.
The function basically performs a binary comparison of both strings’ characters until they differ or until a terminating null character is reached.
C
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <stdio.h> // Function to implement strcmp function int strcmp(const char *X, const char *Y) { while (*X) { // if characters differ, or end of the second string is reached if (*X != *Y) { break; } // move to the next pair of characters X++; Y++; } // return the ASCII difference after converting `char*` to `unsigned char*` return *(const unsigned char*)X - *(const unsigned char*)Y; } // Implement `strcmp()` function in C int main() { char *X = "Techie"; char *Y = "Tech"; int ret = strcmp(X, Y); if (ret > 0) { printf("%s", "X is greater than Y"); } else if (ret < 0) { printf("%s", "X is less than Y"); } else { printf("%s", "X is equal to Y"); } return 0; } |
Output:
X is greater than Y
The time complexity of the above solution is O(min(n, m)), where n and m are the lengths of the two strings.
Excercise: Implement strncmp() function in C
That’s all about strcmp() implementation in C.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)