019
20.10.2003, 12:19 Uhr
virtual
Sexiest Bit alive (Operator)
|
Da haste aber glück: ich habe grade sowas zufälligerweise grade fertig geschrieben (Igitt, muß grade C machen!) - Vorgefertigt gibt es da aber nichts: Bisher nicht in die Tiefe getestet:
C++: |
/** like_compare * This compares the a key and a string, whereas the key may contain wildcards: * '?' - Means one arb. character * '*' - Means 0-N arb. characters * @param <code>key</code> Key to compare * @param <code>str</code> String to compare * @return -1, if mismatch, 0 if exact match. If the value is positive, the * match is as better as smaller the result is. */ int like_compare( const char* key, const char* str) { int match = 0; size_t len = 0;
/* * Assert parameters */ if (NULL==key || NULL==str) { return -1; }
/* * Loop to consume the entire key */ len = strlen(str); while (*key) { size_t var_min = 0; int var_max = 0; size_t fix_len = 0; size_t i=0;
/* * analye next portion of key. * */ while ('?'==*key || '*'==*key) { if ('?'==*key++) ++var_min; else var_max = 1; } while (key[fix_len] && '?'!=key[fix_len] && '*'!=key[fix_len]) { ++fix_len; }
/* * Check minimum count of unspecified characters (number of '?') */ if (len<var_min) { /* str too short */ return -1; } str += var_min; len -= var_min; match += var_min;
/* * Check next fixed part and variable count of unspecified characters */ if (var_max) { int found = 0;
/* * there is at least one '*' now in key. if no further fixed * text follows, we are ready so far, because this must be the * end of the key */ if (0==fix_len) { match += 2*len; return match; }
/* * Now we have to find the fixed text somewhere in str */ for (i=0; i<len-fix_len && !found; ++i, --len, ++str, match += 2) { found = 0==strncmp(key, str, fix_len); ; } if (!found) { /* mismatch */ return -1; } key += fix_len; str += fix_len-1; }else { /* * There is no '*', so the fixed part must match! */ if (len<fix_len) { /* str too short */ return -1; } for(i=0; i<fix_len; ++i, ++key, ++str, --len) { if (*str != *key) { /* mismatch */ return -1; } } } }
/* * Final check */ if (*str) { /* Mismatch (key too short) */ return -1; }
return match; }
|
-- Gruß, virtual Quote of the Month Ich eß' nur was ein Gesicht hat (Creme 21) |