|
| 1 | + // C program to compare the two strings without using strcmp() function |
| 2 | +#include <stdio.h> |
| 3 | +#define str_size 100 // Declare the maximum size of the string |
| 4 | + |
| 5 | +// Function to compare two strings |
| 6 | +int test(char* s1, char* s2) { |
| 7 | + int flag = 0; // Initialize a flag variable to indicate string equality or inequality |
| 8 | + |
| 9 | + // Loop to compare characters in the strings until null terminator '\0' is found in both strings |
| 10 | + while (*s1 != '\0' || *s2 != '\0') { |
| 11 | + if (*s1 == *s2) { // Check if the characters in both strings are equal |
| 12 | + s1++; // Move to the next character in the first string |
| 13 | + s2++; // Move to the next character in the second string |
| 14 | + } else if ((*s1 == '\0' && *s2 != '\0') || (*s1 != '\0' && *s2 == '\0') || *s1 != *s2) { |
| 15 | + // Check for cases where one string ends before the other or characters at the same index are not equal |
| 16 | + flag = 1; // Set the flag to indicate inequality |
| 17 | + break; // Exit the loop as inequality is found |
| 18 | + } |
| 19 | + } |
| 20 | + return flag; // Return the flag indicating string equality (0) or inequality (1) |
| 21 | +} |
| 22 | + |
| 23 | +// Main function |
| 24 | +int main(void) { |
| 25 | + char str1[str_size], str2[str_size]; // Declare character arrays for the two strings |
| 26 | + int flg = 0; // Initialize a flag variable |
| 27 | + |
| 28 | + printf("\nInput the 1st string : "); |
| 29 | + fgets(str1, sizeof str1, stdin); // Read the first string from the standard input (keyboard) |
| 30 | + printf("Input the 2nd string : "); |
| 31 | + fgets(str2, sizeof str2, stdin); // Read the second string from the standard input (keyboard) |
| 32 | + |
| 33 | + printf("\nString1: %s", str1); // Display the first string |
| 34 | + printf("String2: %s", str2); // Display the second string |
| 35 | + |
| 36 | + flg = test(str1, str2); // Call the function to compare the strings |
| 37 | + |
| 38 | + // Display the comparison result based on the flag value |
| 39 | + if (flg == 0) { |
| 40 | + printf("\nStrings are equal.\n"); |
| 41 | + } else if (flg == 1) { |
| 42 | + printf("\nStrings are not equal."); |
| 43 | + } |
| 44 | + |
| 45 | + return 0; // Return 0 to indicate successful program execution |
| 46 | +} |
0 commit comments