Arrays and Strings
String Compare
A character-by-character comparison decides whether two strings contain the same text.
String Compare
string_compare.c
#include <stdio.h>
int sameText(const char left[], const char right[]) {
int i = 0;
while (left[i] != '\0' && right[i] != '\0') {
if (left[i] != right[i]) {
return 0;
}
i++;
}
return left[i] == right[i];
}
int main(void) {
char first[] = "cat";
char second[] = "car";
char third[] = "cat";
int useSecond = ;
const char *other = useSecond ? second : third;
int same = sameText(first, other);
printf("same=%d\n", same);
return 0;
}
#include <stdio.h>
int sameText(const char left[], const char right[]) {
int i = 0;
while (left[i] != '\0' && right[i] != '\0') {
if (left[i] != right[i]) {
return 0;
}
i++;
}
return left[i] == right[i];
}
int main(void) {
char first[] = "cat";
char second[] = "car";
char third[] = "cat";
int useSecond = ;
const char *other = useSecond ? second : third;
int same = sameText(first, other);
printf("same=%d\n", same);
return 0;
}
compare loop
The loop advances while characters match and neither string has ended.
equality result
Two strings are equal only when both reach `'\0'` at the same position.