#include int numcmp(const char *s1, const char *s2) { const char *p1 = s1; const char *p2 = s2; // go past leading zeros while (*p1 == '0') p1++; while (*p2 == '0') p2++; // count the characters in the leading integer portions of the strings const char *decimal1 = p1; const char *decimal2 = p2; while (*decimal1 != 0 && *decimal1 != '.') decimal1++; while (*decimal2 != 0 && *decimal2 != '.') decimal2++; size_t count1 = decimal1 - p1; size_t count2 = decimal2 - p2; // longer integers are bigger if (count1 < count2) return -1; if (count1 > count2) return 1; // There are the same number of digits in the integer portions of the string // so now compare all the characters in the integer string individually while (p1 != decimal1) { // NOTE: its unnecessary to test p2 != decimal2, since char counts are equal char c1 = *p1++; char c2 = *p2++; if (c1 < c2 ) return -1; if (c1 > c2) return 1; } // advance pointers past decimal point if (*p1 == '.') p1++; if (*p2 == '.') p2++; // now compare the fractional portion of the string // do this until the characters differ or a string ends while (*p1 != 0 && *p2 != 0) { char c1 = *p1++; char c2 = *p2++; if (c1 < c2 ) return -1; if (c1 > c2) return 1; } // skip past any zero characters that remain in the strings // (at least one string is at the null now, but we // need not explicitly test) while (*p1 == '0') p1++; while (*p2 == '0') p2++; // compare the final characters (one string may still have more characters // but it doesn't matter). The only possible characters are NULL // and '1' through '9' ('0' is not possible, we explicitly skipped them). // The NULL character will act as a '0' however for comparison purposes if (*p1 < *p2 ) return -1; if (*p1 > *p2) return 1; return 0; } void check( int expect, const char *s1, const char *s2 ) { int res; res = numcmp(s1, s2); if( res > 1 ) res = 1; else if( res < -1 ) res = -1; if( res != expect ) printf(" whoops! %s , %s = %d\n", s1, s2, res); } int main(int argc, char* argv[]) { check( 1,"321", "54" ); check(-1,"54", "321" ); check( 1,"321.6", "00054" ); check(-1,"54", "000321.6" ); check( 1,"321.6", "54.7" ); check(-1,"54.000", "321.0" ); check( 1,"321.6", "54.00000" ); check(-1,"54.00000", "00000321.6" ); check( 0,"0", "0000000.000000000000"); check( 0,"123.", "123.00000000"); check( 0,"123.000", "123"); check( 1,"123.001", "123"); check(-1,"123", "123.001"); check( 0,"123", "123."); check( 1,"123", ".123"); check(-1,"00000100000.0001", "00000100000.0002"); check(-1,"1234567890.", "1234567891."); check(-1,".1234567890", ".1234567891"); check( 1,"12345.0001", "0001234.0001"); check( 1,"0512345.0001", "0412345.0001"); check(-1,"0512345.0001", "0612345.0001"); return 0; }