Advertisement
ZoriaRPG

[C99, C+] Verbose String Comparison

Feb 27th, 2020
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. /* If the value of strcmp is non-zero, this tells you two things:
  2. 1. The two strings do not match.
  3. 2. The difference of the char value at the first string index that was mismatched.
  4. 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.
  5. There is honestly nothing special or magical about how strcmp works…
  6.  
  7. Here's an example of a custom implementation.
  8. */
  9.  
  10. enum
  11. {
  12.     strERR_NOERROR = 0, strERR_A_IS_SMALLER = 10000, strERR_B_IS_SMALLER,
  13.     strERR_NO_NULL_A, strERR_NO_NULL_B, strERR_STRLEN_MISMATCH,
  14.     strERR_CHARACTERS_MISMATCH, strERR_LAST
  15. }; //enum
  16. int verbose_stringcompare(char *a, char *b, char log, int max = 1024)
  17. {
  18.    
  19.     int q = 0, w = 0; //string lengths
  20.     for ( ; q <= max; ++q )
  21.     {
  22.         //sanity check for null termination
  23.         if ( a[q] == NULL ) break;
  24.     }
  25.     if ( q == max )
  26.     {
  27.         //no null termination of A
  28.         if ( log ) printf("No NULL termination on string passed: verbose_stringcompare(*a)\n");
  29.         return strERR_NO_NULL_A;
  30.     }
  31.     for ( ; w <= max; ++w )
  32.     {
  33.         //sanity check for null termination
  34.         if ( b[w] == NULL ) break;
  35.     }
  36.     if ( w == max )
  37.     {
  38.         //no null termination of A
  39.         if ( log ) printf("No NULL termination on string passed: verbose_stringcompare(*b)\n");
  40.         return strERR_NO_NULL_B;
  41.     }
  42.     if ( q != w )
  43.     {
  44.         if ( log ) printf("verbose_stringcompare(a*, *b): Strings differ by length of $d\n", abs(q-w));
  45.         return strERR_STRLEN_MISMATCH;
  46.     }
  47.     // Now parse forwards; lengths match
  48.     for ( int ln = 0; ln < q; ++ ln )
  49.     {
  50.         if ( a[ln] != b[ln] )
  51.         {
  52.             if ( log ) printf("verbose_stringcompare(a*, *b): Character *b[%d] differs by of %d from *a[%d]\n", ln, (a[ln] - b[ln]), ln);
  53.             return strERR_CHARACTERS_MISMATCH;
  54.         }
  55.     }
  56.     return strERR_NOERROR;
  57.        
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement