Implement strcmp() function in C

Write an efficient function to implement strcmp function in C. Standard strcmp() function compares the two strings and returns an integer indicating the relationship between the two strings.

 
 

The prototype of 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 characters of both strings until the characters differ or until a terminating null-character is reached.

C++

Download   Run Code

Output:

X is greater than Y

 
The time complexity of above solution is O(min(n, m)) where n and m are length of the two strings.
 

 
Excercise: Implement strncmp() function in C

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Rodrigo Simas
Guest

the problem is when *X=”abc” and *Y=”abc\0″ your program prints X is equal to Y when in reality X is less than Y

Rodrigo Simas
Guest

never mind, the C function has the same behaviour