I was assigned by my teacher to write my own strcmp()
function in C. I did create my own version of said function, and I was hoping to get some feedback.
int CompareTwoStrings ( char *StringOne, char *StringTwo ) {
// Evaluates if both strings have the same length.
if ( strlen ( StringOne ) != strlen ( StringTwo ) ) {
// Given that the strings have an unequal length, it compares between both
// lengths.
if ( strlen ( StringOne ) < strlen ( StringTwo ) ) {
return ( StringOneIsLesser );
}
if ( strlen ( StringOne ) > strlen ( StringTwo ) ) {
return ( StringOneIsGreater );
}
}
int i;
// Since both strings are equal in length...
for ( i = 0; i < strlen ( StringOne ); i++ ) {
// It goes comparing letter per letter.
if ( StringOne [ i ] != StringTwo [ i ] ) {
if ( StringOne [ i ] < StringTwo [ i ] ) {
return ( StringOneIsLesser );
}
if ( StringOne [ i ] > StringTwo [ i ] ) {
return ( StringOneIsGreater );
}
}
}
// If it ever reaches this part, it means they are equal.
return ( StringsAreEqual );
}
StringOneIsLesser, StringOneIsGreater, StringsAreEqual are defined as const int with the respective values: -1, +1, 0.
Thing is, I'm not exactly sure if, for example, my StringOne has a lesser length than my StringTwo, that automatically means StringTwo is greater, because I don't know how strcmp()
is particularly implemented. I need some of your feedback for that.
strcmp
implementation body can easily be written in 3 lines... move the two pointers forward while they point to identical characters (being careful to stop at the string terminators), and then just compare the characters you reached, which will be the first differing. – Babbagestrcmp()
typically only has to look at the first character to find a difference. That's a big performance hit if the strings are many kilobytes in length. – Cube