Reputation: 1357
i just started learning character arrays in c
. i am just looking at the example 10.4
mentioned in c programming by kochan
.
// 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;
return areEqual;
}
int main (void) {
bool equalStrings (const char s1[], const char s2[]);
const char stra[] = "string compare test";
const char strb[] = "string";
printf ("%i\n", equalStrings (stra, strb));
printf ("%i\n", equalStrings (stra, stra));
printf ("%i\n", equalStrings (strb, "string"));
return 0;
}
i have a few questions about the string equality itself
In the above program, they just started comparing both the characters in the string. doesn't it mean that if two strings are equal, they should be of same length?. if yes, why didn't they compare the length first before they dived into comparing the characters?
does strings have any other comparison operations?. when i googled, i got things like strings similarity, strings identical or not. Any explanation about them would be great.
Upvotes: 0
Views: 51
Reputation: 543
In order to know the length you gave iterate over the string. Give this, it is possible to figure out if they are not equal faster than calculating the length first.
Upvotes: 1
Reputation: 63481
They didn't need to compare the length because these strings are null-terminated. So, if you get to the end of either string, and you have reached the end of the other string too, they must therefore be the same length.
In C's string library, there are other comparison functions. The most common are strcmp
and strncmp
. They will tell you whether strings or substrings are equal, less than or greater than eachother (using an ordering based on actual integer values of each character).
Upvotes: 2