/* * Program to define and demonstrate a function that compares * strings in the way that a lot of programs do now -- * skipping leading white space and ignoring case. */ #include #include #include #include int custom_compare(char * s1, char * s2); void test_compare(char * s1, char * s2); int main(void) { /* simple tests first */ test_compare("aaaa", "aaaa"); test_compare("abcd", "efgh"); test_compare("aaab", "aaaa"); /* now tests with unequal lengths */ test_compare("aa", "aaaa"); test_compare("aaaa", "aa"); /* now tests with leading space, case differences */ test_compare(" hello", "HELLO"); test_compare("hello", " HELLO"); return 0; } void test_compare(char * s1, char * s2) { printf("inputs:\n"); printf("%s\n", s1); printf("%s\n", s2); int result = custom_compare(s1, s2); if (result < 0) { printf("first is first\n"); } else if (result > 0) { printf("second is first\n"); } else { printf("equal\n"); } printf("\n"); } /* * skips leading whitespace, returning pointer to first * nonspace. */ char * skip_ws(char * s) { char * p = s; while (isspace(*p) && (*p != '\0')) { ++p; } return p; } /* * compares strings skipping leading whitespace and * ignoring case. * * return positive, negative, or zero value like that * returned by strcmp(). */ int custom_compare(char * s1, char * s2) { /* * pointers into both strings -- initialize to point to * first nonspace. */ char * p1 = skip_ws(s1); char * p2 = skip_ws(s2); /* * advance through strings, comparing characters, * until either one doesn't match or we come to the * end of either string. */ while ((*p1 != '\0') && (*p2 != '\0')) { char ch1 = tolower(*p1); char ch2 = tolower(*p2); if (ch1 < ch2) return -1; if (ch1 > ch2) return 1; ++p1; ++p2; } /* * if we get here, strings match up to the point * where one or the other (or both) ends */ if (*p1 != '\0') return 1; if (*p2 != '\0') return -1; /* * if we get here, we got to the end of both strings */ return 0; }