strcmp.c
K&R, p. 106
download
#include <stdio.h> // for printf(), scanf(), putchar()
#define SIZE 100 // array size
int strcmp1(char*, char*);
int strcmp2(char*, char*);
int main()
{
char s[SIZE], t[SIZE];
int compare;
printf("Type a word: ");
scanf("%s", s);
printf("Type another word: ");
scanf("%s", t);
printf("%s ", s);
compare = strcmp1(s, t);
if (compare > 0) {putchar('>');}
else if (compare < 0) {putchar('<');}
else {putchar('=');}
printf(" %s\n", t);
printf("%s ", s);
compare = strcmp2(s, t);
if (compare > 0) {putchar('>');}
else if (compare < 0) {putchar('<');}
else {putchar('=');}
printf(" %s\n", t);
return 0;
}
// compare s, t, return < 0 for s < t, 0 for s == t, > 0 for s > t:
int strcmp1(char *s, char *t)
{
int i;
for (i = 0; s[i] && t[i]; i++) // (s[i] != '\0') && (t[i] != '\0')
{
if (s[i] != t[i]) {return s[i] - t[i];}
}
return s[i] - t[i];
}
// compare s, t, return < 0 for s < t, 0 for s == t, > 0 for s > t:
int strcmp2(char *s, char *t)
{
for ( ; *s == *t; s++, t++)
{
if (*s == '\0') {return 0;} // if (!*s) {return *s;}
}
return *s - *t;
}
/*
gcc strcmp.c -o strcmp
./strcmp
Type a word: ana
Type another word: anna
ana < anna
ana < anna
./strcmp
Type a word: card
Type another word: cardboard
card < cardboard
card < cardboard
./strcmp
Type a word: funny
Type another word: fun
funny > fun
funny > fun
./strcmp
Type a word: abracadabra
Type another word: abracadabra
abracadabra = abracadabra
abracadabra = abracadabra
/strcmp
Type a word: -123
Type another word: 102
-123 < 102
-123 < 102
./strcmp
Type a word: 123
Type another word: 1204
123 > 1204
123 > 1204
./strcmp
Type a word: 0
Type another word: 00
0 < 00
0 < 00
/strcmp
Type a word: -1
Type another word: +1
-1 > +1
-1 > +1
*/
Comments
Post a Comment