Compare Two Strings using Character Arrays
To compare two strings using character arrays in C, we can use the built-in function strcmp()
from the string.h
library or manually compare characters using loops. The strcmp()
function checks character-by-character and returns an integer indicating whether the strings are equal, or which one is lexicographically greater.
Examples of String Comparison
1. Comparing Two Strings Using strcmp()
In this example, we will compare two strings using the strcmp()
function. It returns:
0
if both strings are equal.- A negative value if the first string is smaller.
- A positive value if the first string is greater.
main.c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("The strings are equal.");
} else if (result < 0) {
printf("\"%s\" is smaller than \"%s\".", str1, str2);
} else {
printf("\"%s\" is greater than \"%s\".", str1, str2);
}
return 0;
}
Explanation:
- We declare two character arrays,
str1
andstr2
, containing “Hello” and “World”. - We use the
strcmp()
function to compare the two strings and store the result inresult
. - We use an
if
–else
condition to check the returned value:
Output:
"Hello" is smaller than "World".
2. Comparing Two Strings Without strcmp()
In this example, we will compare two strings manually using a while loop. We will iterate through each character and check if they are equal.
main.c
#include <stdio.h>
int compareStrings(char str1[], char str2[]) {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return str1[i] - str2[i];
}
i++;
}
return str1[i] - str2[i];
}
int main() {
char str1[] = "Apple";
char str2[] = "Apple";
int result = compareStrings(str1, str2);
if (result == 0) {
printf("The strings are equal.");
} else if (result < 0) {
printf("\"%s\" is smaller than \"%s\".", str1, str2);
} else {
printf("\"%s\" is greater than \"%s\".", str1, str2);
}
return 0;
}
Explanation:
- We define a function
compareStrings()
to compare two strings manually. - We iterate through both strings using a
while
loop until we find a mismatch or reach the null character ('\0'
). - If characters are different, we return the difference of ASCII values.
- Otherwise, we return 0 if both strings are identical.
- We call
compareStrings()
inmain()
and handle the comparison results usingif
–else
.
Output:
The strings are equal.
Conclusion
In this tutorial, we learned different ways to compare two strings using character arrays in C:
- Using
strcmp()
: A built-in function that compares two strings and returns an integer. - Without
strcmp()
: A manual approach using loops to compare character by character.
Using strcmp()
is recommended for simplicity and efficiency, but understanding the manual approach helps in learning the fundamentals of string comparison in C.