Check The Programming Section
To compare the equality of two strings we can use follwoing library functions. As follows:
strcmp()
stricmp() - Not supported in GNU GCC Compiler
strcasecmp() - presents in strings.h header file
Syntax of strcmp()
int strcmp(char *str1, char *str2);
strcmp compares string character by character. If the first character of two strings is equal, the next character of two strings are compared. This continues until the corresponding characters of two strings are different or a null character '\0' is reached. strcmp did not consdier the case of a character. While compare upper case characters are not considered as same as lower case characters. For this function upper case ('L') and lowe case ('l') will be considered as two different characters.
Return Value
0, if str1 and str2 are same
< 0, if the ASCII value of the first unmatched character of str1 is less than the corresponding character of str2.
> 0, if the ASCII value of the first unmatched character of str1 is greater than the the corresponding character of str2.
The required code is as follows:
Syntax of strcasecmp()
int strcasecmp(const char *string1, const char *string2);
To use this function we need to include strings.h header file. The strcasecmp() function compares string1 and string2 without sensitivity to case. All alphabetic characters in string1 and string2 are converted to lowercase before comparison.
The strcasecmp() function operates on null terminated strings. The string arguments to the function are expected to contain a null character ('\0') marking the end of the string.
Less than 0, if string1 less than string2
equal to 0, if string1 equivalent to string2
Greater than 0, if string1 greater than string2
The required Code is as follows:
Instead of using library functions to compare two strings are equal or not we can design a user defined function and compare character by character. The required steps to design a user defined function can be as follows:
Declare two character array
Take input two strings
pass both the charcater array as argument to a user defined function
Declare a loop index variable and initialised to zero (0)
First check the length of two strings
if same, then follow step 6
else return 0, to the calling function
Compare character by character of both the string till the null character
if first characters of both string matched follow step 7 and comparision need to be done in three level
str1[i] == str2[i], for comparing same case character or
str1[i] == str2[i]-32, for comparing lower case character with upper case or
str1[i] == str2[i]+32, for comparing upper case character with lower case
else return 0, to the calling function
Continue the loop till the null character
if matching is found
else return 0 to the calling function
Return 1 to the calling function
In the calling function, check the value return by the function
if 1, then print both string is equal
else not same