Programming in C

(Barry) #1

204 Chapter 10 Character Strings


Testing Two Character Strings for Equality


You cannot directly test two strings to see if they are equal with a statement such as
if ( string1 == string2 )
...
because the equality operator can only be applied to simple variable types, such as
floats,ints, or chars, and not to more sophisticated types, such as structures or arrays.
To determine if two strings are equal, you must explicitly compare the two character
strings character by character. If you reach the end of both character strings at the same
time, and if all of the characters up to that point are identical, the two strings are equal;
otherwise, they are not.
It might be a good idea to develop a function that can be used to compare two char-
acter strings, as shown in Program 10.4.You can call the function equalStringsand
have it take as arguments the two character strings to be compared. Because you are only
interested in determining whether the two character strings are equal, you can have the
function return a boolval ue of true(or nonzero) if the two strings are identical, and
false(or zero) if they are not. In this way, the function can be used directly inside test
statements, such as in
if ( equalStrings (string1, string2) )
...

Program 10.4 Testing Strings for Equality
// Function to determine if two strings are equal

#include <stdio.h>
#include <stdbool.h>

bool equalStrings (const char s1[], const char s2[])
{
int i = 0;
bool areEqual;

while ( s1[i] == s2 [i] &&
s1[i] != '\0' && s2[i] != '\0' )
++i;

if ( s1[i] == '\0' && s2[i] == '\0' )
areEqual = true;
else
areEqual = false;
Free download pdf