[E-4]Write a function stringCompare(char
const *left, char const *right ) that compares two strings. If the strings
are equal, then the function returns 0. If the strings are not equal, return
a negative value if the left string is shorter than or occurs alphabetically
before the right string. Otherwise, return a positive value.
| Value of stringCompare( left, right ) | |
| left equal to right | 0 |
| left less than right | negative |
| left greater than right | positive |
The value that is returned is determined by the first character position at which the strings differ. Say that the character at this position in the left string is L and the character at this position in the right string is R. Then the function returns (L-R). Here is a testing program:
/* Puzzle S12 -- string compare*/
#include <stdio.h>
#include <stdlib.h>
int stringCompare( char const *left, char const *right )
{
}
int main(int argc, char *argv[])
{
char *trials[][2] =
{
{"a", "a"},
{"a", "f"},
{"abc", "abc"},
{"abc", "def"},
{"abcdef", "abcdef"},
{"abcdef", "aaaaaa"},
{"abcdeff", "abcdef"},
{"abcdef", "xabcdef"},
{"xabcdef", "abcdef"},
{"abcdef", "rats"},
{"abbccf", "cc"},
{"abcdefg", "g"},
{"apple", ""},
{"", "apple"},
{"",""},
{"green", "green"},
{"ASBC", "ASBC"},
{" ", " "},
{"12345", "12345"},
{"++-!@#", "++-!@#"},
{"tab\ttab", "tab\ttab"}
};
int j;
for ( j=0; j<sizeof(trials)/sizeof(trials[0]); j++ )
{
int result = stringCompare( trials[j][0], trials[j][1] ) ;
if ( result==0 )
printf("%s\t==\t%s\n", trials[j][0], trials[j][1] );
else if ( result<0)
printf("%s\t<\t%s\n", trials[j][0], trials[j][1] );
else
printf("%s\t>\t%s\n", trials[j][0], trials[j][1] );
}
return 0;
}
Write this function by making a single character change to the answer for puzzle S11.
Note: this function is similar to the function strcmp()
described in <string.h>.
However,
strcmp() is not required to return any particular positive
or negative value for dissimilar strings.
In professional-level code,
use the standard function rather than your own.