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 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <string>
int comp(const char* a, const char* b) {
while (*a && *b && *a == *b) // while corresponding characters are not nul and are equal
++a, ++b; // advance the pointers.
// At this point one of two things has happened:
// - A nul character was found indicating the end of one (or both) of the strings.
// - Corresponding characters were encountered that were not equal
// Therefore, if *a is equal to *b, then the strings are equal.
if (*a == *b) return 0;
// At this point it is a given that *a is not equal to *b
// If both *a and *b are not end-of-string, then if *a is less than *b,
// a should come before b.
if (*a && *b) return *a - *b;
// At this point it is a given that one of our pointers is at end-of-string.
// The one that is should come before the other.
return *a ? 1 : -1;
}
bool results_equivalent(int v1, int v2) {
if (v1 == 0 && v2 == 0) return true;
if (v1 < 0 && v2 < 0) return true;
if (v1 > 0 && v2 > 0) return true;
return false;
}
void test(const char* s1, const char* s2) {
int result = comp(s1, s2);
int expected = std::string(s1).compare(s2);
bool equivalent = results_equivalent(result, expected);
std::cout << (equivalent ? "** CORRECT ** " : "** INCORRECT **");
std::cout << " \tcomp(\"" << s1 << "\", \"" << s2 << "\") is " << result << '\n';
}
int main()
{
test("John", "Johnson");
test("John", "John");
test("abc", "abd");
test("dba", "cba");
test("Hammerpants", "Hammer");
}
|