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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz