đ§đģ Tutorial: Compare Two Strings in C (With & Without strcmp()
)
In this tutorial, you will learn how to compare two strings entered by the user using:
- ✅ The built-in
strcmp()
function from<string.h>
- đ ️ Manual comparison character by character (without using string functions)
✅ Method 1: Using strcmp()
Function
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
// Remove newline characters if present
size_t len1 = strlen(str1);
if (len1 > 0 && str1[len1 - 1] == '\n') {
str1[len1 - 1] = '\0';
}
size_t len2 = strlen(str2);
if (len2 > 0 && str2[len2 - 1] == '\n') {
str2[len2 - 1] = '\0';
}
// Compare using strcmp()
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
đ Explanation:
fgets()
is used to input strings safely.- Trailing newline characters are removed.
strcmp()
compares both strings.- Returns 0 if equal, non-zero otherwise.
đ ️ Method 2: Without Using strcmp()
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i = 0, flag = 0;
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
// Remove newline characters
while (str1[i] != '\0') {
if (str1[i] == '\n') {
str1[i] = '\0';
break;
}
i++;
}
i = 0;
while (str2[i] != '\0') {
if (str2[i] == '\n') {
str2[i] = '\0';
break;
}
i++;
}
// Manual comparison
i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
flag = 1;
break;
}
i++;
}
if (str1[i] != str2[i]) {
flag = 1; // Different lengths
}
if (flag == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
đ Explanation:
- Both strings are compared character-by-character.
- Newline characters are removed manually.
- Flag is used to track differences.
- This method does not use any string library function.
đ Summary
You’ve learned how to compare two strings in C using both strcmp()
and manual logic. The built-in function is easier and more reliable, but manual comparison helps build core logic skills.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ