Code Snippets

  

C Source Code



Another strcmp

Another version of strcmp but in 3 statements

Submitted By: Martyn.Rae
Actions:
Rating:
Views: 1,869

Language: C

Last Modified: February 15, 2010

Snippet


  1. int strcmp(const char* firstString, const char* secondString) {
  2.         for( ; *firstString == *secondString && *firstString != 0 && *secondString != 0; firstString++, secondString++ );
  3.         if ( !*firstString && !*secondString ) return 0;
  4.         return *firstString - *secondString;
  5. }
  6.  

Copy & Paste


Comments

David W 2010-02-14 07:20:40

but fails this test: char t1[] = "12345"; char t2[] = "123456"; printf( "strcmp(t1, t2) = %d\n", strcmp( t1, t2 ) ); /* 0 */ printf( "strcmp(t2, t1) = %d\n", strcmp( t2, t1 ) ); /* 1 */

David W 2010-02-14 07:41:13

try this: int strcmp(const char* firstString, const char* secondString) { for( ; *firstString == *secondString && *firstString != 0 && *secondString != 0; firstString++, secondString++ ); if ( !*firstString && !*secondString ) return 0; return *firstString - *secondString; }

Martyn.Rae 2010-02-14 20:51:19

Thank you to David W for bringing this error to my attention. The snippet above has been corrected.

David W 2010-02-16 02:50:03

And thank you for all your help to so many students at DIC. BTW ... have you taken a look at HLA, by Randy Hyde? You, Martyn, as an assembly programmer, may be enthralled with what's happening there. For an example of strcmp ignoring case, this DIC link may be useful: http://www.dreamincode.net/code/snippet5070.htm


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.