In this exercise I am using Visual Studio 2017 and the std_lib_facilities header provided by Stroustrup.
Chapter 18 // Exercise 3Write a function, int strcmp(const char* s1, const char* s2), that compares C-style strings. Let it return a negative number if s1 is lexicographically before s2, zero if s1 equals s2, and a positive number if s1 is lexicographically after s2. Do not use any standard library functions. Do not use subscripting; use the dereference operator * instead.
I thought I had this in the bag by just comparing the C-style strings with < and > like you can with strings but I temporarily forgot that this only compares the first character instead. This is a problem if you have words like 'chili' and 'chilly'. So I calculated the shortest length (don't want to be accessing random memory if one of the variables is shorter than the other) and checked to see if each character was either less than the other character or equal to it. If one of them was true, continue to check, if both are false than the entire string is alphabetically after the other. I also used a bool to keep track if the first character was before as the next one may be after and that would return 1 for instances like "bra" and "zebra" as b is before z but r is after e.
No comments:
Post a Comment