Code:
#include <stdio.h>
#include <string.h>
int strmtcmp(char*,char*);
int main() {
char a[] = "hello world";
char b[] = "hello wo";
int res = strmtcmp(a,b);
if (res>0)
printf("'%s' is 'larger' than '%s'\n",a,b);
else if (res<0)
printf("'%s' is 'smaller' than '%s'\n",a,b);
else
printf("'%s' is the same as '%s'\n",a,b);
/* prove it is correct */
printf("%d - %d\n",res,strcmp(a,b));
return 0;
}
int strmtcmp(char* a,char* b) {
while( *a != '\0' /* not at end of string 1 */
&& *b != '\0' /* not at end of string 2 */
&& *a == *b ) /* they are the same at the same char */
{
a++; b++; /* move to next element */
}
/* finished the loop - either a is null, b is null, or the chars differ */
return (*a - *b);
}
Code:
[email protected] [11:01 PM] '~'
> $ gcc -Wall -o flavius flavius.c && ./flavius
'hello world' is 'larger' than 'hello wo'
114 - 114