Geeks With Blogs
Chris Breisch   .NET Data Practices
Search this Blog!

/* compare two strings

* return -1 if s1 < s2, 1 if s1 > s2, 0 if equal

*/

int strcmp(char *s1, char *s2) {

for(;*s1==*s2;++s1,++s2)

if(!(*s1))

return 0;

return (*s1<*s2)? -1 : 1;

}

/*

* Compare two strings terminated by NULL_CHAR (‘\0’)

* return 0 if they are equal,

*       -1 if the first is less than the second, and

*        1 if the first is greater than the second

* Two null strings are considered equal and a null

* string is considered to be less than a non-null string

*/

int StringCompare(char *string1, char *string2)

{

char difference = 0; /* ASCII difference between two characters */

/* check for null strings first */

if (string1 == null && string2 == null)

return 0;

if (string1 == null)

return -1;

if (string2 == null)

return 1;

/* loop until we find a terminator in string1

* and check each character.  As soon as we find a

* different character, return

*/

while (*string1 != NULL_CHAR)

{

difference = *string1 – *string2;

if (difference == 0)

{

*string1++;

*string2++;

}

else

{

/* we want to return -1/+1 rather

than the ASCII difference */

return (difference < 0) ? -1 : 1;

}

}

/* if we got here, we made it through string1

* so check whether there’s more to string2

*/

if (*string2 != NULL_CHAR)

{

return -1;

}

else

{

return 0;

}

}

Related Posts on Geeks With Blogs Matching Categories

Comments on this post: A Long Blog Entry for a Long Book

# re: A Long Blog Entry for a Long Book

CC2E is a great book but dedication to reading it is the only thing that will get you through the massive undertaking. I've been picking it up and putting it down for months now.
Left by Eric Hammersley on Sep 09, 2005 8:47 AM

# re: A Long Blog Entry for a Long Book
Hey Chris,

At first Object Thinking will seem tedious to read but stick with it, the book gets better as it goes and has a lot of "aha" moments in it.
Left by Steven R on Sep 09, 2005 9:05 AM

# re: A Long Blog Entry for a Long Book
I found Code Complete to be a completely boring read, stating obvious conclusions at best. Maybe this is because I have decades of experience behind me but anyway, it's a great book to get into right before "lights out" if you're not tired. BTW, I agree wholeheartedly on exceptions.
Left by Brian on Sep 09, 2005 10:07 AM