Write a C program to compare two strings without using built-in function(strcmp).
#include <stdlib.h>
#include <string.h>
int main() {
char str1[64], str2[64], i = 0, flag = 0;
/* get the first input string */
printf("Enter your 1st string:");
fgets(str1, 64, stdin);
str1[strlen(str1) - 1] = '\0';
/* get the second input string */
printf("Enter your 2nd string:");
fgets(str2, 64, stdin);
str2[strlen(str2) - 1] = '\0';
/* compare lenght of two strings */
if (strlen(str1) != strlen(str2)) {
printf("Both string are not equal\n");
return;
}
/* compare each and every character in both string */
while (str1[i] != '\0') {
if (str1[i] != str2[i]) {
flag = 1;
break;
}
i++;
}
/* print the result */
if (flag)
printf("Both strings are not same\n");
else
printf("Both strings are same\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your 1st string : HelloWorld
Enter your 2nd string : HelloWorld
Both strings are same
Enter your 1st string : HelloWorld
Enter your 2nd string : HelloWorld
Both strings are same
No comments:
Post a Comment