Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* If the value of strcmp is non-zero, this tells you two things:
- 1. The two strings do not match.
- 2. The difference of the char value at the first string index that was mismatched.
- You can write your own functions to provide different results, if you desire, such as returning nonzero on match, or providing additional data. *e.g.,* It can be useful to print out where the string comparison halted (the index), and the value of the indices of all strings being compared at that index as char.
- There is honestly nothing special or magical about how strcmp works…
- Here's an example of a custom implementation.
- */
- enum
- {
- strERR_NOERROR = 0, strERR_A_IS_SMALLER = 10000, strERR_B_IS_SMALLER,
- strERR_NO_NULL_A, strERR_NO_NULL_B, strERR_STRLEN_MISMATCH,
- strERR_CHARACTERS_MISMATCH, strERR_LAST
- }; //enum
- int verbose_stringcompare(char *a, char *b, char log, int max = 1024)
- {
- int q = 0, w = 0; //string lengths
- for ( ; q <= max; ++q )
- {
- //sanity check for null termination
- if ( a[q] == NULL ) break;
- }
- if ( q == max )
- {
- //no null termination of A
- if ( log ) printf("No NULL termination on string passed: verbose_stringcompare(*a)\n");
- return strERR_NO_NULL_A;
- }
- for ( ; w <= max; ++w )
- {
- //sanity check for null termination
- if ( b[w] == NULL ) break;
- }
- if ( w == max )
- {
- //no null termination of A
- if ( log ) printf("No NULL termination on string passed: verbose_stringcompare(*b)\n");
- return strERR_NO_NULL_B;
- }
- if ( q != w )
- {
- if ( log ) printf("verbose_stringcompare(a*, *b): Strings differ by length of $d\n", abs(q-w));
- return strERR_STRLEN_MISMATCH;
- }
- // Now parse forwards; lengths match
- for ( int ln = 0; ln < q; ++ ln )
- {
- if ( a[ln] != b[ln] )
- {
- if ( log ) printf("verbose_stringcompare(a*, *b): Character *b[%d] differs by of %d from *a[%d]\n", ln, (a[ln] - b[ln]), ln);
- return strERR_CHARACTERS_MISMATCH;
- }
- }
- return strERR_NOERROR;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement